PackageManagerService.java revision 1dfb21b673471aa8780e2b44b362a70f4675cb49
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
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_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.system.OsConstants.O_CREAT;
88import static android.system.OsConstants.O_RDWR;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
91import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
92import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
93import static com.android.internal.util.ArrayUtils.appendInt;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
105
106import android.Manifest;
107import android.annotation.IntDef;
108import android.annotation.NonNull;
109import android.annotation.Nullable;
110import android.app.ActivityManager;
111import android.app.AppOpsManager;
112import android.app.IActivityManager;
113import android.app.ResourcesManager;
114import android.app.admin.IDevicePolicyManager;
115import android.app.admin.SecurityLog;
116import android.app.backup.IBackupManager;
117import android.content.BroadcastReceiver;
118import android.content.ComponentName;
119import android.content.ContentResolver;
120import android.content.Context;
121import android.content.IIntentReceiver;
122import android.content.Intent;
123import android.content.IntentFilter;
124import android.content.IntentSender;
125import android.content.IntentSender.SendIntentException;
126import android.content.ServiceConnection;
127import android.content.pm.ActivityInfo;
128import android.content.pm.ApplicationInfo;
129import android.content.pm.AppsQueryHelper;
130import android.content.pm.AuxiliaryResolveInfo;
131import android.content.pm.ChangedPackages;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppRequest;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.ServiceInfo;
168import android.content.pm.SharedLibraryInfo;
169import android.content.pm.Signature;
170import android.content.pm.UserInfo;
171import android.content.pm.VerifierDeviceIdentity;
172import android.content.pm.VerifierInfo;
173import android.content.pm.VersionedPackage;
174import android.content.res.Resources;
175import android.database.ContentObserver;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.BootTimingsTraceLog;
225import android.util.DisplayMetrics;
226import android.util.EventLog;
227import android.util.ExceptionUtils;
228import android.util.Log;
229import android.util.LogPrinter;
230import android.util.MathUtils;
231import android.util.PackageUtils;
232import android.util.Pair;
233import android.util.PrintStreamPrinter;
234import android.util.Slog;
235import android.util.SparseArray;
236import android.util.SparseBooleanArray;
237import android.util.SparseIntArray;
238import android.util.Xml;
239import android.util.jar.StrictJarFile;
240import android.util.proto.ProtoOutputStream;
241import android.view.Display;
242
243import com.android.internal.R;
244import com.android.internal.annotations.GuardedBy;
245import com.android.internal.app.IMediaContainerService;
246import com.android.internal.app.ResolverActivity;
247import com.android.internal.content.NativeLibraryHelper;
248import com.android.internal.content.PackageHelper;
249import com.android.internal.logging.MetricsLogger;
250import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251import com.android.internal.os.IParcelFileDescriptorFactory;
252import com.android.internal.os.RoSystemProperties;
253import com.android.internal.os.SomeArgs;
254import com.android.internal.os.Zygote;
255import com.android.internal.telephony.CarrierAppUtils;
256import com.android.internal.util.ArrayUtils;
257import com.android.internal.util.ConcurrentUtils;
258import com.android.internal.util.DumpUtils;
259import com.android.internal.util.FastPrintWriter;
260import com.android.internal.util.FastXmlSerializer;
261import com.android.internal.util.IndentingPrintWriter;
262import com.android.internal.util.Preconditions;
263import com.android.internal.util.XmlUtils;
264import com.android.server.AttributeCache;
265import com.android.server.DeviceIdleController;
266import com.android.server.EventLogTags;
267import com.android.server.FgThread;
268import com.android.server.IntentResolver;
269import com.android.server.LocalServices;
270import com.android.server.LockGuard;
271import com.android.server.ServiceThread;
272import com.android.server.SystemConfig;
273import com.android.server.SystemServerInitThreadPool;
274import com.android.server.Watchdog;
275import com.android.server.net.NetworkPolicyManagerInternal;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.lang.annotation.Retention;
307import java.lang.annotation.RetentionPolicy;
308import java.nio.charset.StandardCharsets;
309import java.security.DigestInputStream;
310import java.security.MessageDigest;
311import java.security.NoSuchAlgorithmException;
312import java.security.PublicKey;
313import java.security.SecureRandom;
314import java.security.cert.Certificate;
315import java.security.cert.CertificateEncodingException;
316import java.security.cert.CertificateException;
317import java.text.SimpleDateFormat;
318import java.util.ArrayList;
319import java.util.Arrays;
320import java.util.Collection;
321import java.util.Collections;
322import java.util.Comparator;
323import java.util.Date;
324import java.util.HashMap;
325import java.util.HashSet;
326import java.util.Iterator;
327import java.util.List;
328import java.util.Map;
329import java.util.Objects;
330import java.util.Set;
331import java.util.concurrent.CountDownLatch;
332import java.util.concurrent.Future;
333import java.util.concurrent.TimeUnit;
334import java.util.concurrent.atomic.AtomicBoolean;
335import java.util.concurrent.atomic.AtomicInteger;
336
337/**
338 * Keep track of all those APKs everywhere.
339 * <p>
340 * Internally there are two important locks:
341 * <ul>
342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
343 * and other related state. It is a fine-grained lock that should only be held
344 * momentarily, as it's one of the most contended locks in the system.
345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
346 * operations typically involve heavy lifting of application data on disk. Since
347 * {@code installd} is single-threaded, and it's operations can often be slow,
348 * this lock should never be acquired while already holding {@link #mPackages}.
349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
350 * holding {@link #mInstallLock}.
351 * </ul>
352 * Many internal methods rely on the caller to hold the appropriate locks, and
353 * this contract is expressed through method name suffixes:
354 * <ul>
355 * <li>fooLI(): the caller must hold {@link #mInstallLock}
356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
357 * being modified must be frozen
358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
360 * </ul>
361 * <p>
362 * Because this class is very central to the platform's security; please run all
363 * CTS and unit tests whenever making modifications:
364 *
365 * <pre>
366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
368 * </pre>
369 */
370public class PackageManagerService extends IPackageManager.Stub
371        implements PackageSender {
372    static final String TAG = "PackageManager";
373    static final boolean DEBUG_SETTINGS = false;
374    static final boolean DEBUG_PREFERRED = false;
375    static final boolean DEBUG_UPGRADE = false;
376    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
377    private static final boolean DEBUG_BACKUP = false;
378    private static final boolean DEBUG_INSTALL = false;
379    private static final boolean DEBUG_REMOVE = false;
380    private static final boolean DEBUG_BROADCASTS = false;
381    private static final boolean DEBUG_SHOW_INFO = false;
382    private static final boolean DEBUG_PACKAGE_INFO = false;
383    private static final boolean DEBUG_INTENT_MATCHING = false;
384    private static final boolean DEBUG_PACKAGE_SCANNING = false;
385    private static final boolean DEBUG_VERIFY = false;
386    private static final boolean DEBUG_FILTERS = false;
387    private static final boolean DEBUG_PERMISSIONS = false;
388    private static final boolean DEBUG_SHARED_LIBRARIES = false;
389
390    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
391    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
392    // user, but by default initialize to this.
393    public static final boolean DEBUG_DEXOPT = false;
394
395    private static final boolean DEBUG_ABI_SELECTION = false;
396    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
397    private static final boolean DEBUG_TRIAGED_MISSING = false;
398    private static final boolean DEBUG_APP_DATA = false;
399
400    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
401    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
402
403    private static final boolean HIDE_EPHEMERAL_APIS = false;
404
405    private static final boolean ENABLE_FREE_CACHE_V2 =
406            SystemProperties.getBoolean("fw.free_cache_v2", true);
407
408    private static final int RADIO_UID = Process.PHONE_UID;
409    private static final int LOG_UID = Process.LOG_UID;
410    private static final int NFC_UID = Process.NFC_UID;
411    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
412    private static final int SHELL_UID = Process.SHELL_UID;
413
414    // Cap the size of permission trees that 3rd party apps can define
415    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
416
417    // Suffix used during package installation when copying/moving
418    // package apks to install directory.
419    private static final String INSTALL_PACKAGE_SUFFIX = "-";
420
421    static final int SCAN_NO_DEX = 1<<1;
422    static final int SCAN_FORCE_DEX = 1<<2;
423    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
424    static final int SCAN_NEW_INSTALL = 1<<4;
425    static final int SCAN_UPDATE_TIME = 1<<5;
426    static final int SCAN_BOOTING = 1<<6;
427    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
428    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
429    static final int SCAN_REPLACING = 1<<9;
430    static final int SCAN_REQUIRE_KNOWN = 1<<10;
431    static final int SCAN_MOVE = 1<<11;
432    static final int SCAN_INITIAL = 1<<12;
433    static final int SCAN_CHECK_ONLY = 1<<13;
434    static final int SCAN_DONT_KILL_APP = 1<<14;
435    static final int SCAN_IGNORE_FROZEN = 1<<15;
436    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
437    static final int SCAN_AS_INSTANT_APP = 1<<17;
438    static final int SCAN_AS_FULL_APP = 1<<18;
439    /** Should not be with the scan flags */
440    static final int FLAGS_REMOVE_CHATTY = 1<<31;
441
442    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
443
444    private static final int[] EMPTY_INT_ARRAY = new int[0];
445
446    private static final int TYPE_UNKNOWN = 0;
447    private static final int TYPE_ACTIVITY = 1;
448    private static final int TYPE_RECEIVER = 2;
449    private static final int TYPE_SERVICE = 3;
450    private static final int TYPE_PROVIDER = 4;
451    @IntDef(prefix = { "TYPE_" }, value = {
452            TYPE_UNKNOWN,
453            TYPE_ACTIVITY,
454            TYPE_RECEIVER,
455            TYPE_SERVICE,
456            TYPE_PROVIDER,
457    })
458    @Retention(RetentionPolicy.SOURCE)
459    public @interface ComponentType {}
460
461    /**
462     * Timeout (in milliseconds) after which the watchdog should declare that
463     * our handler thread is wedged.  The usual default for such things is one
464     * minute but we sometimes do very lengthy I/O operations on this thread,
465     * such as installing multi-gigabyte applications, so ours needs to be longer.
466     */
467    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
468
469    /**
470     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
471     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
472     * settings entry if available, otherwise we use the hardcoded default.  If it's been
473     * more than this long since the last fstrim, we force one during the boot sequence.
474     *
475     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
476     * one gets run at the next available charging+idle time.  This final mandatory
477     * no-fstrim check kicks in only of the other scheduling criteria is never met.
478     */
479    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
480
481    /**
482     * Whether verification is enabled by default.
483     */
484    private static final boolean DEFAULT_VERIFY_ENABLE = true;
485
486    /**
487     * The default maximum time to wait for the verification agent to return in
488     * milliseconds.
489     */
490    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
491
492    /**
493     * The default response for package verification timeout.
494     *
495     * This can be either PackageManager.VERIFICATION_ALLOW or
496     * PackageManager.VERIFICATION_REJECT.
497     */
498    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
499
500    static final String PLATFORM_PACKAGE_NAME = "android";
501
502    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
503
504    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
505            DEFAULT_CONTAINER_PACKAGE,
506            "com.android.defcontainer.DefaultContainerService");
507
508    private static final String KILL_APP_REASON_GIDS_CHANGED =
509            "permission grant or revoke changed gids";
510
511    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
512            "permissions revoked";
513
514    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
515
516    private static final String PACKAGE_SCHEME = "package";
517
518    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
519
520    /** Permission grant: not grant the permission. */
521    private static final int GRANT_DENIED = 1;
522
523    /** Permission grant: grant the permission as an install permission. */
524    private static final int GRANT_INSTALL = 2;
525
526    /** Permission grant: grant the permission as a runtime one. */
527    private static final int GRANT_RUNTIME = 3;
528
529    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
530    private static final int GRANT_UPGRADE = 4;
531
532    /** Canonical intent used to identify what counts as a "web browser" app */
533    private static final Intent sBrowserIntent;
534    static {
535        sBrowserIntent = new Intent();
536        sBrowserIntent.setAction(Intent.ACTION_VIEW);
537        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
538        sBrowserIntent.setData(Uri.parse("http:"));
539    }
540
541    /**
542     * The set of all protected actions [i.e. those actions for which a high priority
543     * intent filter is disallowed].
544     */
545    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
546    static {
547        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
548        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
549        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
550        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
551    }
552
553    // Compilation reasons.
554    public static final int REASON_FIRST_BOOT = 0;
555    public static final int REASON_BOOT = 1;
556    public static final int REASON_INSTALL = 2;
557    public static final int REASON_BACKGROUND_DEXOPT = 3;
558    public static final int REASON_AB_OTA = 4;
559
560    public static final int REASON_LAST = REASON_AB_OTA;
561
562    /** All dangerous permission names in the same order as the events in MetricsEvent */
563    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
564            Manifest.permission.READ_CALENDAR,
565            Manifest.permission.WRITE_CALENDAR,
566            Manifest.permission.CAMERA,
567            Manifest.permission.READ_CONTACTS,
568            Manifest.permission.WRITE_CONTACTS,
569            Manifest.permission.GET_ACCOUNTS,
570            Manifest.permission.ACCESS_FINE_LOCATION,
571            Manifest.permission.ACCESS_COARSE_LOCATION,
572            Manifest.permission.RECORD_AUDIO,
573            Manifest.permission.READ_PHONE_STATE,
574            Manifest.permission.CALL_PHONE,
575            Manifest.permission.READ_CALL_LOG,
576            Manifest.permission.WRITE_CALL_LOG,
577            Manifest.permission.ADD_VOICEMAIL,
578            Manifest.permission.USE_SIP,
579            Manifest.permission.PROCESS_OUTGOING_CALLS,
580            Manifest.permission.READ_CELL_BROADCASTS,
581            Manifest.permission.BODY_SENSORS,
582            Manifest.permission.SEND_SMS,
583            Manifest.permission.RECEIVE_SMS,
584            Manifest.permission.READ_SMS,
585            Manifest.permission.RECEIVE_WAP_PUSH,
586            Manifest.permission.RECEIVE_MMS,
587            Manifest.permission.READ_EXTERNAL_STORAGE,
588            Manifest.permission.WRITE_EXTERNAL_STORAGE,
589            Manifest.permission.READ_PHONE_NUMBERS,
590            Manifest.permission.ANSWER_PHONE_CALLS);
591
592
593    /**
594     * Version number for the package parser cache. Increment this whenever the format or
595     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
596     */
597    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
598
599    /**
600     * Whether the package parser cache is enabled.
601     */
602    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
603
604    final ServiceThread mHandlerThread;
605
606    final PackageHandler mHandler;
607
608    private final ProcessLoggingHandler mProcessLoggingHandler;
609
610    /**
611     * Messages for {@link #mHandler} that need to wait for system ready before
612     * being dispatched.
613     */
614    private ArrayList<Message> mPostSystemReadyMessages;
615
616    final int mSdkVersion = Build.VERSION.SDK_INT;
617
618    final Context mContext;
619    final boolean mFactoryTest;
620    final boolean mOnlyCore;
621    final DisplayMetrics mMetrics;
622    final int mDefParseFlags;
623    final String[] mSeparateProcesses;
624    final boolean mIsUpgrade;
625    final boolean mIsPreNUpgrade;
626    final boolean mIsPreNMR1Upgrade;
627
628    // Have we told the Activity Manager to whitelist the default container service by uid yet?
629    @GuardedBy("mPackages")
630    boolean mDefaultContainerWhitelisted = false;
631
632    @GuardedBy("mPackages")
633    private boolean mDexOptDialogShown;
634
635    /** The location for ASEC container files on internal storage. */
636    final String mAsecInternalPath;
637
638    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
639    // LOCK HELD.  Can be called with mInstallLock held.
640    @GuardedBy("mInstallLock")
641    final Installer mInstaller;
642
643    /** Directory where installed third-party apps stored */
644    final File mAppInstallDir;
645
646    /**
647     * Directory to which applications installed internally have their
648     * 32 bit native libraries copied.
649     */
650    private File mAppLib32InstallDir;
651
652    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
653    // apps.
654    final File mDrmAppPrivateInstallDir;
655
656    // ----------------------------------------------------------------
657
658    // Lock for state used when installing and doing other long running
659    // operations.  Methods that must be called with this lock held have
660    // the suffix "LI".
661    final Object mInstallLock = new Object();
662
663    // ----------------------------------------------------------------
664
665    // Keys are String (package name), values are Package.  This also serves
666    // as the lock for the global state.  Methods that must be called with
667    // this lock held have the prefix "LP".
668    @GuardedBy("mPackages")
669    final ArrayMap<String, PackageParser.Package> mPackages =
670            new ArrayMap<String, PackageParser.Package>();
671
672    final ArrayMap<String, Set<String>> mKnownCodebase =
673            new ArrayMap<String, Set<String>>();
674
675    // Keys are isolated uids and values are the uid of the application
676    // that created the isolated proccess.
677    @GuardedBy("mPackages")
678    final SparseIntArray mIsolatedOwners = new SparseIntArray();
679
680    /**
681     * Tracks new system packages [received in an OTA] that we expect to
682     * find updated user-installed versions. Keys are package name, values
683     * are package location.
684     */
685    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
686    /**
687     * Tracks high priority intent filters for protected actions. During boot, certain
688     * filter actions are protected and should never be allowed to have a high priority
689     * intent filter for them. However, there is one, and only one exception -- the
690     * setup wizard. It must be able to define a high priority intent filter for these
691     * actions to ensure there are no escapes from the wizard. We need to delay processing
692     * of these during boot as we need to look at all of the system packages in order
693     * to know which component is the setup wizard.
694     */
695    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
696    /**
697     * Whether or not processing protected filters should be deferred.
698     */
699    private boolean mDeferProtectedFilters = true;
700
701    /**
702     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
703     */
704    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
705    /**
706     * Whether or not system app permissions should be promoted from install to runtime.
707     */
708    boolean mPromoteSystemApps;
709
710    @GuardedBy("mPackages")
711    final Settings mSettings;
712
713    /**
714     * Set of package names that are currently "frozen", which means active
715     * surgery is being done on the code/data for that package. The platform
716     * will refuse to launch frozen packages to avoid race conditions.
717     *
718     * @see PackageFreezer
719     */
720    @GuardedBy("mPackages")
721    final ArraySet<String> mFrozenPackages = new ArraySet<>();
722
723    final ProtectedPackages mProtectedPackages;
724
725    boolean mFirstBoot;
726
727    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
728
729    // System configuration read by SystemConfig.
730    final int[] mGlobalGids;
731    final SparseArray<ArraySet<String>> mSystemPermissions;
732    @GuardedBy("mAvailableFeatures")
733    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
734
735    // If mac_permissions.xml was found for seinfo labeling.
736    boolean mFoundPolicyFile;
737
738    private final InstantAppRegistry mInstantAppRegistry;
739
740    @GuardedBy("mPackages")
741    int mChangedPackagesSequenceNumber;
742    /**
743     * List of changed [installed, removed or updated] packages.
744     * mapping from user id -> sequence number -> package name
745     */
746    @GuardedBy("mPackages")
747    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
748    /**
749     * The sequence number of the last change to a package.
750     * mapping from user id -> package name -> sequence number
751     */
752    @GuardedBy("mPackages")
753    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
754
755    class PackageParserCallback implements PackageParser.Callback {
756        @Override public final boolean hasFeature(String feature) {
757            return PackageManagerService.this.hasSystemFeature(feature, 0);
758        }
759
760        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
761                Collection<PackageParser.Package> allPackages, String targetPackageName) {
762            List<PackageParser.Package> overlayPackages = null;
763            for (PackageParser.Package p : allPackages) {
764                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
765                    if (overlayPackages == null) {
766                        overlayPackages = new ArrayList<PackageParser.Package>();
767                    }
768                    overlayPackages.add(p);
769                }
770            }
771            if (overlayPackages != null) {
772                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
773                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
774                        return p1.mOverlayPriority - p2.mOverlayPriority;
775                    }
776                };
777                Collections.sort(overlayPackages, cmp);
778            }
779            return overlayPackages;
780        }
781
782        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
783                String targetPackageName, String targetPath) {
784            if ("android".equals(targetPackageName)) {
785                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786                // native AssetManager.
787                return null;
788            }
789            List<PackageParser.Package> overlayPackages =
790                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
791            if (overlayPackages == null || overlayPackages.isEmpty()) {
792                return null;
793            }
794            List<String> overlayPathList = null;
795            for (PackageParser.Package overlayPackage : overlayPackages) {
796                if (targetPath == null) {
797                    if (overlayPathList == null) {
798                        overlayPathList = new ArrayList<String>();
799                    }
800                    overlayPathList.add(overlayPackage.baseCodePath);
801                    continue;
802                }
803
804                try {
805                    // Creates idmaps for system to parse correctly the Android manifest of the
806                    // target package.
807                    //
808                    // OverlayManagerService will update each of them with a correct gid from its
809                    // target package app id.
810                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
811                            UserHandle.getSharedAppGid(
812                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
813                    if (overlayPathList == null) {
814                        overlayPathList = new ArrayList<String>();
815                    }
816                    overlayPathList.add(overlayPackage.baseCodePath);
817                } catch (InstallerException e) {
818                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
819                            overlayPackage.baseCodePath);
820                }
821            }
822            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
823        }
824
825        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
826            synchronized (mPackages) {
827                return getStaticOverlayPathsLocked(
828                        mPackages.values(), targetPackageName, targetPath);
829            }
830        }
831
832        @Override public final String[] getOverlayApks(String targetPackageName) {
833            return getStaticOverlayPaths(targetPackageName, null);
834        }
835
836        @Override public final String[] getOverlayPaths(String targetPackageName,
837                String targetPath) {
838            return getStaticOverlayPaths(targetPackageName, targetPath);
839        }
840    };
841
842    class ParallelPackageParserCallback extends PackageParserCallback {
843        List<PackageParser.Package> mOverlayPackages = null;
844
845        void findStaticOverlayPackages() {
846            synchronized (mPackages) {
847                for (PackageParser.Package p : mPackages.values()) {
848                    if (p.mIsStaticOverlay) {
849                        if (mOverlayPackages == null) {
850                            mOverlayPackages = new ArrayList<PackageParser.Package>();
851                        }
852                        mOverlayPackages.add(p);
853                    }
854                }
855            }
856        }
857
858        @Override
859        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
860            // We can trust mOverlayPackages without holding mPackages because package uninstall
861            // can't happen while running parallel parsing.
862            // Moreover holding mPackages on each parsing thread causes dead-lock.
863            return mOverlayPackages == null ? null :
864                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
865        }
866    }
867
868    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
869    final ParallelPackageParserCallback mParallelPackageParserCallback =
870            new ParallelPackageParserCallback();
871
872    public static final class SharedLibraryEntry {
873        public final @Nullable String path;
874        public final @Nullable String apk;
875        public final @NonNull SharedLibraryInfo info;
876
877        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
878                String declaringPackageName, int declaringPackageVersionCode) {
879            path = _path;
880            apk = _apk;
881            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
882                    declaringPackageName, declaringPackageVersionCode), null);
883        }
884    }
885
886    // Currently known shared libraries.
887    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
888    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
889            new ArrayMap<>();
890
891    // All available activities, for your resolving pleasure.
892    final ActivityIntentResolver mActivities =
893            new ActivityIntentResolver();
894
895    // All available receivers, for your resolving pleasure.
896    final ActivityIntentResolver mReceivers =
897            new ActivityIntentResolver();
898
899    // All available services, for your resolving pleasure.
900    final ServiceIntentResolver mServices = new ServiceIntentResolver();
901
902    // All available providers, for your resolving pleasure.
903    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
904
905    // Mapping from provider base names (first directory in content URI codePath)
906    // to the provider information.
907    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
908            new ArrayMap<String, PackageParser.Provider>();
909
910    // Mapping from instrumentation class names to info about them.
911    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
912            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
913
914    // Mapping from permission names to info about them.
915    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
916            new ArrayMap<String, PackageParser.PermissionGroup>();
917
918    // Packages whose data we have transfered into another package, thus
919    // should no longer exist.
920    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
921
922    // Broadcast actions that are only available to the system.
923    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
924
925    /** List of packages waiting for verification. */
926    final SparseArray<PackageVerificationState> mPendingVerification
927            = new SparseArray<PackageVerificationState>();
928
929    /** Set of packages associated with each app op permission. */
930    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
931
932    final PackageInstallerService mInstallerService;
933
934    private final PackageDexOptimizer mPackageDexOptimizer;
935    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
936    // is used by other apps).
937    private final DexManager mDexManager;
938
939    private AtomicInteger mNextMoveId = new AtomicInteger();
940    private final MoveCallbacks mMoveCallbacks;
941
942    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
943
944    // Cache of users who need badging.
945    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
946
947    /** Token for keys in mPendingVerification. */
948    private int mPendingVerificationToken = 0;
949
950    volatile boolean mSystemReady;
951    volatile boolean mSafeMode;
952    volatile boolean mHasSystemUidErrors;
953    private volatile boolean mEphemeralAppsDisabled;
954
955    ApplicationInfo mAndroidApplication;
956    final ActivityInfo mResolveActivity = new ActivityInfo();
957    final ResolveInfo mResolveInfo = new ResolveInfo();
958    ComponentName mResolveComponentName;
959    PackageParser.Package mPlatformPackage;
960    ComponentName mCustomResolverComponentName;
961
962    boolean mResolverReplaced = false;
963
964    private final @Nullable ComponentName mIntentFilterVerifierComponent;
965    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
966
967    private int mIntentFilterVerificationToken = 0;
968
969    /** The service connection to the ephemeral resolver */
970    final EphemeralResolverConnection mInstantAppResolverConnection;
971    /** Component used to show resolver settings for Instant Apps */
972    final ComponentName mInstantAppResolverSettingsComponent;
973
974    /** Activity used to install instant applications */
975    ActivityInfo mInstantAppInstallerActivity;
976    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
977
978    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
979            = new SparseArray<IntentFilterVerificationState>();
980
981    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
982
983    // List of packages names to keep cached, even if they are uninstalled for all users
984    private List<String> mKeepUninstalledPackages;
985
986    private UserManagerInternal mUserManagerInternal;
987
988    private DeviceIdleController.LocalService mDeviceIdleController;
989
990    private File mCacheDir;
991
992    private ArraySet<String> mPrivappPermissionsViolations;
993
994    private Future<?> mPrepareAppDataFuture;
995
996    private static class IFVerificationParams {
997        PackageParser.Package pkg;
998        boolean replacing;
999        int userId;
1000        int verifierUid;
1001
1002        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1003                int _userId, int _verifierUid) {
1004            pkg = _pkg;
1005            replacing = _replacing;
1006            userId = _userId;
1007            replacing = _replacing;
1008            verifierUid = _verifierUid;
1009        }
1010    }
1011
1012    private interface IntentFilterVerifier<T extends IntentFilter> {
1013        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1014                                               T filter, String packageName);
1015        void startVerifications(int userId);
1016        void receiveVerificationResponse(int verificationId);
1017    }
1018
1019    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1020        private Context mContext;
1021        private ComponentName mIntentFilterVerifierComponent;
1022        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1023
1024        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1025            mContext = context;
1026            mIntentFilterVerifierComponent = verifierComponent;
1027        }
1028
1029        private String getDefaultScheme() {
1030            return IntentFilter.SCHEME_HTTPS;
1031        }
1032
1033        @Override
1034        public void startVerifications(int userId) {
1035            // Launch verifications requests
1036            int count = mCurrentIntentFilterVerifications.size();
1037            for (int n=0; n<count; n++) {
1038                int verificationId = mCurrentIntentFilterVerifications.get(n);
1039                final IntentFilterVerificationState ivs =
1040                        mIntentFilterVerificationStates.get(verificationId);
1041
1042                String packageName = ivs.getPackageName();
1043
1044                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1045                final int filterCount = filters.size();
1046                ArraySet<String> domainsSet = new ArraySet<>();
1047                for (int m=0; m<filterCount; m++) {
1048                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1049                    domainsSet.addAll(filter.getHostsList());
1050                }
1051                synchronized (mPackages) {
1052                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1053                            packageName, domainsSet) != null) {
1054                        scheduleWriteSettingsLocked();
1055                    }
1056                }
1057                sendVerificationRequest(userId, verificationId, ivs);
1058            }
1059            mCurrentIntentFilterVerifications.clear();
1060        }
1061
1062        private void sendVerificationRequest(int userId, int verificationId,
1063                IntentFilterVerificationState ivs) {
1064
1065            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1066            verificationIntent.putExtra(
1067                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1068                    verificationId);
1069            verificationIntent.putExtra(
1070                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1071                    getDefaultScheme());
1072            verificationIntent.putExtra(
1073                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1074                    ivs.getHostsString());
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1077                    ivs.getPackageName());
1078            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1079            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1080
1081            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1082            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1083                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1084                    userId, false, "intent filter verifier");
1085
1086            UserHandle user = new UserHandle(userId);
1087            mContext.sendBroadcastAsUser(verificationIntent, user);
1088            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1089                    "Sending IntentFilter verification broadcast");
1090        }
1091
1092        public void receiveVerificationResponse(int verificationId) {
1093            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1094
1095            final boolean verified = ivs.isVerified();
1096
1097            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1098            final int count = filters.size();
1099            if (DEBUG_DOMAIN_VERIFICATION) {
1100                Slog.i(TAG, "Received verification response " + verificationId
1101                        + " for " + count + " filters, verified=" + verified);
1102            }
1103            for (int n=0; n<count; n++) {
1104                PackageParser.ActivityIntentInfo filter = filters.get(n);
1105                filter.setVerified(verified);
1106
1107                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1108                        + " verified with result:" + verified + " and hosts:"
1109                        + ivs.getHostsString());
1110            }
1111
1112            mIntentFilterVerificationStates.remove(verificationId);
1113
1114            final String packageName = ivs.getPackageName();
1115            IntentFilterVerificationInfo ivi = null;
1116
1117            synchronized (mPackages) {
1118                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1119            }
1120            if (ivi == null) {
1121                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1122                        + verificationId + " packageName:" + packageName);
1123                return;
1124            }
1125            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1126                    "Updating IntentFilterVerificationInfo for package " + packageName
1127                            +" verificationId:" + verificationId);
1128
1129            synchronized (mPackages) {
1130                if (verified) {
1131                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1132                } else {
1133                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1134                }
1135                scheduleWriteSettingsLocked();
1136
1137                final int userId = ivs.getUserId();
1138                if (userId != UserHandle.USER_ALL) {
1139                    final int userStatus =
1140                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1141
1142                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1143                    boolean needUpdate = false;
1144
1145                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1146                    // already been set by the User thru the Disambiguation dialog
1147                    switch (userStatus) {
1148                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1149                            if (verified) {
1150                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1151                            } else {
1152                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1153                            }
1154                            needUpdate = true;
1155                            break;
1156
1157                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1158                            if (verified) {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1160                                needUpdate = true;
1161                            }
1162                            break;
1163
1164                        default:
1165                            // Nothing to do
1166                    }
1167
1168                    if (needUpdate) {
1169                        mSettings.updateIntentFilterVerificationStatusLPw(
1170                                packageName, updatedStatus, userId);
1171                        scheduleWritePackageRestrictionsLocked(userId);
1172                    }
1173                }
1174            }
1175        }
1176
1177        @Override
1178        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1179                    ActivityIntentInfo filter, String packageName) {
1180            if (!hasValidDomains(filter)) {
1181                return false;
1182            }
1183            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1184            if (ivs == null) {
1185                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1186                        packageName);
1187            }
1188            if (DEBUG_DOMAIN_VERIFICATION) {
1189                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1190            }
1191            ivs.addFilter(filter);
1192            return true;
1193        }
1194
1195        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1196                int userId, int verificationId, String packageName) {
1197            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1198                    verifierUid, userId, packageName);
1199            ivs.setPendingState();
1200            synchronized (mPackages) {
1201                mIntentFilterVerificationStates.append(verificationId, ivs);
1202                mCurrentIntentFilterVerifications.add(verificationId);
1203            }
1204            return ivs;
1205        }
1206    }
1207
1208    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1209        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1210                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1211                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1212    }
1213
1214    // Set of pending broadcasts for aggregating enable/disable of components.
1215    static class PendingPackageBroadcasts {
1216        // for each user id, a map of <package name -> components within that package>
1217        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1218
1219        public PendingPackageBroadcasts() {
1220            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1221        }
1222
1223        public ArrayList<String> get(int userId, String packageName) {
1224            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1225            return packages.get(packageName);
1226        }
1227
1228        public void put(int userId, String packageName, ArrayList<String> components) {
1229            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1230            packages.put(packageName, components);
1231        }
1232
1233        public void remove(int userId, String packageName) {
1234            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1235            if (packages != null) {
1236                packages.remove(packageName);
1237            }
1238        }
1239
1240        public void remove(int userId) {
1241            mUidMap.remove(userId);
1242        }
1243
1244        public int userIdCount() {
1245            return mUidMap.size();
1246        }
1247
1248        public int userIdAt(int n) {
1249            return mUidMap.keyAt(n);
1250        }
1251
1252        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1253            return mUidMap.get(userId);
1254        }
1255
1256        public int size() {
1257            // total number of pending broadcast entries across all userIds
1258            int num = 0;
1259            for (int i = 0; i< mUidMap.size(); i++) {
1260                num += mUidMap.valueAt(i).size();
1261            }
1262            return num;
1263        }
1264
1265        public void clear() {
1266            mUidMap.clear();
1267        }
1268
1269        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1270            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1271            if (map == null) {
1272                map = new ArrayMap<String, ArrayList<String>>();
1273                mUidMap.put(userId, map);
1274            }
1275            return map;
1276        }
1277    }
1278    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1279
1280    // Service Connection to remote media container service to copy
1281    // package uri's from external media onto secure containers
1282    // or internal storage.
1283    private IMediaContainerService mContainerService = null;
1284
1285    static final int SEND_PENDING_BROADCAST = 1;
1286    static final int MCS_BOUND = 3;
1287    static final int END_COPY = 4;
1288    static final int INIT_COPY = 5;
1289    static final int MCS_UNBIND = 6;
1290    static final int START_CLEANING_PACKAGE = 7;
1291    static final int FIND_INSTALL_LOC = 8;
1292    static final int POST_INSTALL = 9;
1293    static final int MCS_RECONNECT = 10;
1294    static final int MCS_GIVE_UP = 11;
1295    static final int UPDATED_MEDIA_STATUS = 12;
1296    static final int WRITE_SETTINGS = 13;
1297    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1298    static final int PACKAGE_VERIFIED = 15;
1299    static final int CHECK_PENDING_VERIFICATION = 16;
1300    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1301    static final int INTENT_FILTER_VERIFIED = 18;
1302    static final int WRITE_PACKAGE_LIST = 19;
1303    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1304
1305    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1306
1307    // Delay time in millisecs
1308    static final int BROADCAST_DELAY = 10 * 1000;
1309
1310    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1311            2 * 60 * 60 * 1000L; /* two hours */
1312
1313    static UserManagerService sUserManager;
1314
1315    // Stores a list of users whose package restrictions file needs to be updated
1316    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1317
1318    final private DefaultContainerConnection mDefContainerConn =
1319            new DefaultContainerConnection();
1320    class DefaultContainerConnection implements ServiceConnection {
1321        public void onServiceConnected(ComponentName name, IBinder service) {
1322            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1323            final IMediaContainerService imcs = IMediaContainerService.Stub
1324                    .asInterface(Binder.allowBlocking(service));
1325            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1326        }
1327
1328        public void onServiceDisconnected(ComponentName name) {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1330        }
1331    }
1332
1333    // Recordkeeping of restore-after-install operations that are currently in flight
1334    // between the Package Manager and the Backup Manager
1335    static class PostInstallData {
1336        public InstallArgs args;
1337        public PackageInstalledInfo res;
1338
1339        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1340            args = _a;
1341            res = _r;
1342        }
1343    }
1344
1345    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1346    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1347
1348    // XML tags for backup/restore of various bits of state
1349    private static final String TAG_PREFERRED_BACKUP = "pa";
1350    private static final String TAG_DEFAULT_APPS = "da";
1351    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1352
1353    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1354    private static final String TAG_ALL_GRANTS = "rt-grants";
1355    private static final String TAG_GRANT = "grant";
1356    private static final String ATTR_PACKAGE_NAME = "pkg";
1357
1358    private static final String TAG_PERMISSION = "perm";
1359    private static final String ATTR_PERMISSION_NAME = "name";
1360    private static final String ATTR_IS_GRANTED = "g";
1361    private static final String ATTR_USER_SET = "set";
1362    private static final String ATTR_USER_FIXED = "fixed";
1363    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1364
1365    // System/policy permission grants are not backed up
1366    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1367            FLAG_PERMISSION_POLICY_FIXED
1368            | FLAG_PERMISSION_SYSTEM_FIXED
1369            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1370
1371    // And we back up these user-adjusted states
1372    private static final int USER_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_USER_SET
1374            | FLAG_PERMISSION_USER_FIXED
1375            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1376
1377    final @Nullable String mRequiredVerifierPackage;
1378    final @NonNull String mRequiredInstallerPackage;
1379    final @NonNull String mRequiredUninstallerPackage;
1380    final @Nullable String mSetupWizardPackage;
1381    final @Nullable String mStorageManagerPackage;
1382    final @NonNull String mServicesSystemSharedLibraryPackageName;
1383    final @NonNull String mSharedSystemSharedLibraryPackageName;
1384
1385    final boolean mPermissionReviewRequired;
1386
1387    private final PackageUsage mPackageUsage = new PackageUsage();
1388    private final CompilerStats mCompilerStats = new CompilerStats();
1389
1390    class PackageHandler extends Handler {
1391        private boolean mBound = false;
1392        final ArrayList<HandlerParams> mPendingInstalls =
1393            new ArrayList<HandlerParams>();
1394
1395        private boolean connectToService() {
1396            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1397                    " DefaultContainerService");
1398            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1399            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1400            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1401                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1402                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1403                mBound = true;
1404                return true;
1405            }
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1407            return false;
1408        }
1409
1410        private void disconnectService() {
1411            mContainerService = null;
1412            mBound = false;
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414            mContext.unbindService(mDefContainerConn);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416        }
1417
1418        PackageHandler(Looper looper) {
1419            super(looper);
1420        }
1421
1422        public void handleMessage(Message msg) {
1423            try {
1424                doHandleMessage(msg);
1425            } finally {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427            }
1428        }
1429
1430        void doHandleMessage(Message msg) {
1431            switch (msg.what) {
1432                case INIT_COPY: {
1433                    HandlerParams params = (HandlerParams) msg.obj;
1434                    int idx = mPendingInstalls.size();
1435                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1436                    // If a bind was already initiated we dont really
1437                    // need to do anything. The pending install
1438                    // will be processed later on.
1439                    if (!mBound) {
1440                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1441                                System.identityHashCode(mHandler));
1442                        // If this is the only one pending we might
1443                        // have to bind to the service again.
1444                        if (!connectToService()) {
1445                            Slog.e(TAG, "Failed to bind to media container service");
1446                            params.serviceError();
1447                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448                                    System.identityHashCode(mHandler));
1449                            if (params.traceMethod != null) {
1450                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1451                                        params.traceCookie);
1452                            }
1453                            return;
1454                        } else {
1455                            // Once we bind to the service, the first
1456                            // pending request will be processed.
1457                            mPendingInstalls.add(idx, params);
1458                        }
1459                    } else {
1460                        mPendingInstalls.add(idx, params);
1461                        // Already bound to the service. Just make
1462                        // sure we trigger off processing the first request.
1463                        if (idx == 0) {
1464                            mHandler.sendEmptyMessage(MCS_BOUND);
1465                        }
1466                    }
1467                    break;
1468                }
1469                case MCS_BOUND: {
1470                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1471                    if (msg.obj != null) {
1472                        mContainerService = (IMediaContainerService) msg.obj;
1473                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1474                                System.identityHashCode(mHandler));
1475                    }
1476                    if (mContainerService == null) {
1477                        if (!mBound) {
1478                            // Something seriously wrong since we are not bound and we are not
1479                            // waiting for connection. Bail out.
1480                            Slog.e(TAG, "Cannot bind to media container service");
1481                            for (HandlerParams params : mPendingInstalls) {
1482                                // Indicate service bind error
1483                                params.serviceError();
1484                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1485                                        System.identityHashCode(params));
1486                                if (params.traceMethod != null) {
1487                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1488                                            params.traceMethod, params.traceCookie);
1489                                }
1490                                return;
1491                            }
1492                            mPendingInstalls.clear();
1493                        } else {
1494                            Slog.w(TAG, "Waiting to connect to media container service");
1495                        }
1496                    } else if (mPendingInstalls.size() > 0) {
1497                        HandlerParams params = mPendingInstalls.get(0);
1498                        if (params != null) {
1499                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1500                                    System.identityHashCode(params));
1501                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1502                            if (params.startCopy()) {
1503                                // We are done...  look for more work or to
1504                                // go idle.
1505                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1506                                        "Checking for more work or unbind...");
1507                                // Delete pending install
1508                                if (mPendingInstalls.size() > 0) {
1509                                    mPendingInstalls.remove(0);
1510                                }
1511                                if (mPendingInstalls.size() == 0) {
1512                                    if (mBound) {
1513                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1514                                                "Posting delayed MCS_UNBIND");
1515                                        removeMessages(MCS_UNBIND);
1516                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1517                                        // Unbind after a little delay, to avoid
1518                                        // continual thrashing.
1519                                        sendMessageDelayed(ubmsg, 10000);
1520                                    }
1521                                } else {
1522                                    // There are more pending requests in queue.
1523                                    // Just post MCS_BOUND message to trigger processing
1524                                    // of next pending install.
1525                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                            "Posting MCS_BOUND for next work");
1527                                    mHandler.sendEmptyMessage(MCS_BOUND);
1528                                }
1529                            }
1530                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1531                        }
1532                    } else {
1533                        // Should never happen ideally.
1534                        Slog.w(TAG, "Empty queue");
1535                    }
1536                    break;
1537                }
1538                case MCS_RECONNECT: {
1539                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1540                    if (mPendingInstalls.size() > 0) {
1541                        if (mBound) {
1542                            disconnectService();
1543                        }
1544                        if (!connectToService()) {
1545                            Slog.e(TAG, "Failed to bind to media container service");
1546                            for (HandlerParams params : mPendingInstalls) {
1547                                // Indicate service bind error
1548                                params.serviceError();
1549                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1550                                        System.identityHashCode(params));
1551                            }
1552                            mPendingInstalls.clear();
1553                        }
1554                    }
1555                    break;
1556                }
1557                case MCS_UNBIND: {
1558                    // If there is no actual work left, then time to unbind.
1559                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1560
1561                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1562                        if (mBound) {
1563                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1564
1565                            disconnectService();
1566                        }
1567                    } else if (mPendingInstalls.size() > 0) {
1568                        // There are more pending requests in queue.
1569                        // Just post MCS_BOUND message to trigger processing
1570                        // of next pending install.
1571                        mHandler.sendEmptyMessage(MCS_BOUND);
1572                    }
1573
1574                    break;
1575                }
1576                case MCS_GIVE_UP: {
1577                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1578                    HandlerParams params = mPendingInstalls.remove(0);
1579                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1580                            System.identityHashCode(params));
1581                    break;
1582                }
1583                case SEND_PENDING_BROADCAST: {
1584                    String packages[];
1585                    ArrayList<String> components[];
1586                    int size = 0;
1587                    int uids[];
1588                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1589                    synchronized (mPackages) {
1590                        if (mPendingBroadcasts == null) {
1591                            return;
1592                        }
1593                        size = mPendingBroadcasts.size();
1594                        if (size <= 0) {
1595                            // Nothing to be done. Just return
1596                            return;
1597                        }
1598                        packages = new String[size];
1599                        components = new ArrayList[size];
1600                        uids = new int[size];
1601                        int i = 0;  // filling out the above arrays
1602
1603                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1604                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1605                            Iterator<Map.Entry<String, ArrayList<String>>> it
1606                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1607                                            .entrySet().iterator();
1608                            while (it.hasNext() && i < size) {
1609                                Map.Entry<String, ArrayList<String>> ent = it.next();
1610                                packages[i] = ent.getKey();
1611                                components[i] = ent.getValue();
1612                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1613                                uids[i] = (ps != null)
1614                                        ? UserHandle.getUid(packageUserId, ps.appId)
1615                                        : -1;
1616                                i++;
1617                            }
1618                        }
1619                        size = i;
1620                        mPendingBroadcasts.clear();
1621                    }
1622                    // Send broadcasts
1623                    for (int i = 0; i < size; i++) {
1624                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1625                    }
1626                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1627                    break;
1628                }
1629                case START_CLEANING_PACKAGE: {
1630                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1631                    final String packageName = (String)msg.obj;
1632                    final int userId = msg.arg1;
1633                    final boolean andCode = msg.arg2 != 0;
1634                    synchronized (mPackages) {
1635                        if (userId == UserHandle.USER_ALL) {
1636                            int[] users = sUserManager.getUserIds();
1637                            for (int user : users) {
1638                                mSettings.addPackageToCleanLPw(
1639                                        new PackageCleanItem(user, packageName, andCode));
1640                            }
1641                        } else {
1642                            mSettings.addPackageToCleanLPw(
1643                                    new PackageCleanItem(userId, packageName, andCode));
1644                        }
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                    startCleaningPackages();
1648                } break;
1649                case POST_INSTALL: {
1650                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1651
1652                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1653                    final boolean didRestore = (msg.arg2 != 0);
1654                    mRunningInstalls.delete(msg.arg1);
1655
1656                    if (data != null) {
1657                        InstallArgs args = data.args;
1658                        PackageInstalledInfo parentRes = data.res;
1659
1660                        final boolean grantPermissions = (args.installFlags
1661                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1662                        final boolean killApp = (args.installFlags
1663                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1664                        final String[] grantedPermissions = args.installGrantPermissions;
1665
1666                        // Handle the parent package
1667                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1668                                grantedPermissions, didRestore, args.installerPackageName,
1669                                args.observer);
1670
1671                        // Handle the child packages
1672                        final int childCount = (parentRes.addedChildPackages != null)
1673                                ? parentRes.addedChildPackages.size() : 0;
1674                        for (int i = 0; i < childCount; i++) {
1675                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1676                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1677                                    grantedPermissions, false, args.installerPackageName,
1678                                    args.observer);
1679                        }
1680
1681                        // Log tracing if needed
1682                        if (args.traceMethod != null) {
1683                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1684                                    args.traceCookie);
1685                        }
1686                    } else {
1687                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1688                    }
1689
1690                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1691                } break;
1692                case UPDATED_MEDIA_STATUS: {
1693                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1694                    boolean reportStatus = msg.arg1 == 1;
1695                    boolean doGc = msg.arg2 == 1;
1696                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1697                    if (doGc) {
1698                        // Force a gc to clear up stale containers.
1699                        Runtime.getRuntime().gc();
1700                    }
1701                    if (msg.obj != null) {
1702                        @SuppressWarnings("unchecked")
1703                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1704                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1705                        // Unload containers
1706                        unloadAllContainers(args);
1707                    }
1708                    if (reportStatus) {
1709                        try {
1710                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1711                                    "Invoking StorageManagerService call back");
1712                            PackageHelper.getStorageManager().finishMediaUpdate();
1713                        } catch (RemoteException e) {
1714                            Log.e(TAG, "StorageManagerService not running?");
1715                        }
1716                    }
1717                } break;
1718                case WRITE_SETTINGS: {
1719                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1720                    synchronized (mPackages) {
1721                        removeMessages(WRITE_SETTINGS);
1722                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1723                        mSettings.writeLPr();
1724                        mDirtyUsers.clear();
1725                    }
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1727                } break;
1728                case WRITE_PACKAGE_RESTRICTIONS: {
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730                    synchronized (mPackages) {
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        for (int userId : mDirtyUsers) {
1733                            mSettings.writePackageRestrictionsLPr(userId);
1734                        }
1735                        mDirtyUsers.clear();
1736                    }
1737                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1738                } break;
1739                case WRITE_PACKAGE_LIST: {
1740                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1741                    synchronized (mPackages) {
1742                        removeMessages(WRITE_PACKAGE_LIST);
1743                        mSettings.writePackageListLPr(msg.arg1);
1744                    }
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1746                } break;
1747                case CHECK_PENDING_VERIFICATION: {
1748                    final int verificationId = msg.arg1;
1749                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1750
1751                    if ((state != null) && !state.timeoutExtended()) {
1752                        final InstallArgs args = state.getInstallArgs();
1753                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1754
1755                        Slog.i(TAG, "Verification timed out for " + originUri);
1756                        mPendingVerification.remove(verificationId);
1757
1758                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1759
1760                        final UserHandle user = args.getUser();
1761                        if (getDefaultVerificationResponse(user)
1762                                == PackageManager.VERIFICATION_ALLOW) {
1763                            Slog.i(TAG, "Continuing with installation of " + originUri);
1764                            state.setVerifierResponse(Binder.getCallingUid(),
1765                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1766                            broadcastPackageVerified(verificationId, originUri,
1767                                    PackageManager.VERIFICATION_ALLOW, user);
1768                            try {
1769                                ret = args.copyApk(mContainerService, true);
1770                            } catch (RemoteException e) {
1771                                Slog.e(TAG, "Could not contact the ContainerService");
1772                            }
1773                        } else {
1774                            broadcastPackageVerified(verificationId, originUri,
1775                                    PackageManager.VERIFICATION_REJECT, user);
1776                        }
1777
1778                        Trace.asyncTraceEnd(
1779                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1780
1781                        processPendingInstall(args, ret);
1782                        mHandler.sendEmptyMessage(MCS_UNBIND);
1783                    }
1784                    break;
1785                }
1786                case PACKAGE_VERIFIED: {
1787                    final int verificationId = msg.arg1;
1788
1789                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1790                    if (state == null) {
1791                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1792                        break;
1793                    }
1794
1795                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1796
1797                    state.setVerifierResponse(response.callerUid, response.code);
1798
1799                    if (state.isVerificationComplete()) {
1800                        mPendingVerification.remove(verificationId);
1801
1802                        final InstallArgs args = state.getInstallArgs();
1803                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1804
1805                        int ret;
1806                        if (state.isInstallAllowed()) {
1807                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1808                            broadcastPackageVerified(verificationId, originUri,
1809                                    response.code, state.getInstallArgs().getUser());
1810                            try {
1811                                ret = args.copyApk(mContainerService, true);
1812                            } catch (RemoteException e) {
1813                                Slog.e(TAG, "Could not contact the ContainerService");
1814                            }
1815                        } else {
1816                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1817                        }
1818
1819                        Trace.asyncTraceEnd(
1820                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1821
1822                        processPendingInstall(args, ret);
1823                        mHandler.sendEmptyMessage(MCS_UNBIND);
1824                    }
1825
1826                    break;
1827                }
1828                case START_INTENT_FILTER_VERIFICATIONS: {
1829                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1830                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1831                            params.replacing, params.pkg);
1832                    break;
1833                }
1834                case INTENT_FILTER_VERIFIED: {
1835                    final int verificationId = msg.arg1;
1836
1837                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1838                            verificationId);
1839                    if (state == null) {
1840                        Slog.w(TAG, "Invalid IntentFilter verification token "
1841                                + verificationId + " received");
1842                        break;
1843                    }
1844
1845                    final int userId = state.getUserId();
1846
1847                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1848                            "Processing IntentFilter verification with token:"
1849                            + verificationId + " and userId:" + userId);
1850
1851                    final IntentFilterVerificationResponse response =
1852                            (IntentFilterVerificationResponse) msg.obj;
1853
1854                    state.setVerifierResponse(response.callerUid, response.code);
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "IntentFilter verification with token:" + verificationId
1858                            + " and userId:" + userId
1859                            + " is settings verifier response with response code:"
1860                            + response.code);
1861
1862                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1863                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1864                                + response.getFailedDomainsString());
1865                    }
1866
1867                    if (state.isVerificationComplete()) {
1868                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1869                    } else {
1870                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1871                                "IntentFilter verification with token:" + verificationId
1872                                + " was not said to be complete");
1873                    }
1874
1875                    break;
1876                }
1877                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1878                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1879                            mInstantAppResolverConnection,
1880                            (InstantAppRequest) msg.obj,
1881                            mInstantAppInstallerActivity,
1882                            mHandler);
1883                }
1884            }
1885        }
1886    }
1887
1888    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1889            boolean killApp, String[] grantedPermissions,
1890            boolean launchedForRestore, String installerPackage,
1891            IPackageInstallObserver2 installObserver) {
1892        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1893            // Send the removed broadcasts
1894            if (res.removedInfo != null) {
1895                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1896            }
1897
1898            // Now that we successfully installed the package, grant runtime
1899            // permissions if requested before broadcasting the install. Also
1900            // for legacy apps in permission review mode we clear the permission
1901            // review flag which is used to emulate runtime permissions for
1902            // legacy apps.
1903            if (grantPermissions) {
1904                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1905            }
1906
1907            final boolean update = res.removedInfo != null
1908                    && res.removedInfo.removedPackage != null;
1909            final String origInstallerPackageName = res.removedInfo != null
1910                    ? res.removedInfo.installerPackageName : null;
1911
1912            // If this is the first time we have child packages for a disabled privileged
1913            // app that had no children, we grant requested runtime permissions to the new
1914            // children if the parent on the system image had them already granted.
1915            if (res.pkg.parentPackage != null) {
1916                synchronized (mPackages) {
1917                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1918                }
1919            }
1920
1921            synchronized (mPackages) {
1922                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1923            }
1924
1925            final String packageName = res.pkg.applicationInfo.packageName;
1926
1927            // Determine the set of users who are adding this package for
1928            // the first time vs. those who are seeing an update.
1929            int[] firstUsers = EMPTY_INT_ARRAY;
1930            int[] updateUsers = EMPTY_INT_ARRAY;
1931            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1932            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1933            for (int newUser : res.newUsers) {
1934                if (ps.getInstantApp(newUser)) {
1935                    continue;
1936                }
1937                if (allNewUsers) {
1938                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1939                    continue;
1940                }
1941                boolean isNew = true;
1942                for (int origUser : res.origUsers) {
1943                    if (origUser == newUser) {
1944                        isNew = false;
1945                        break;
1946                    }
1947                }
1948                if (isNew) {
1949                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1950                } else {
1951                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1952                }
1953            }
1954
1955            // Send installed broadcasts if the package is not a static shared lib.
1956            if (res.pkg.staticSharedLibName == null) {
1957                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1958
1959                // Send added for users that see the package for the first time
1960                // sendPackageAddedForNewUsers also deals with system apps
1961                int appId = UserHandle.getAppId(res.uid);
1962                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1963                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1964
1965                // Send added for users that don't see the package for the first time
1966                Bundle extras = new Bundle(1);
1967                extras.putInt(Intent.EXTRA_UID, res.uid);
1968                if (update) {
1969                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1970                }
1971                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1972                        extras, 0 /*flags*/,
1973                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1974                if (origInstallerPackageName != null) {
1975                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1976                            extras, 0 /*flags*/,
1977                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1978                }
1979
1980                // Send replaced for users that don't see the package for the first time
1981                if (update) {
1982                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1983                            packageName, extras, 0 /*flags*/,
1984                            null /*targetPackage*/, null /*finishedReceiver*/,
1985                            updateUsers);
1986                    if (origInstallerPackageName != null) {
1987                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1988                                extras, 0 /*flags*/,
1989                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1990                    }
1991                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1992                            null /*package*/, null /*extras*/, 0 /*flags*/,
1993                            packageName /*targetPackage*/,
1994                            null /*finishedReceiver*/, updateUsers);
1995                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1996                    // First-install and we did a restore, so we're responsible for the
1997                    // first-launch broadcast.
1998                    if (DEBUG_BACKUP) {
1999                        Slog.i(TAG, "Post-restore of " + packageName
2000                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2001                    }
2002                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2003                }
2004
2005                // Send broadcast package appeared if forward locked/external for all users
2006                // treat asec-hosted packages like removable media on upgrade
2007                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2008                    if (DEBUG_INSTALL) {
2009                        Slog.i(TAG, "upgrading pkg " + res.pkg
2010                                + " is ASEC-hosted -> AVAILABLE");
2011                    }
2012                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2013                    ArrayList<String> pkgList = new ArrayList<>(1);
2014                    pkgList.add(packageName);
2015                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2016                }
2017            }
2018
2019            // Work that needs to happen on first install within each user
2020            if (firstUsers != null && firstUsers.length > 0) {
2021                synchronized (mPackages) {
2022                    for (int userId : firstUsers) {
2023                        // If this app is a browser and it's newly-installed for some
2024                        // users, clear any default-browser state in those users. The
2025                        // app's nature doesn't depend on the user, so we can just check
2026                        // its browser nature in any user and generalize.
2027                        if (packageIsBrowser(packageName, userId)) {
2028                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2029                        }
2030
2031                        // We may also need to apply pending (restored) runtime
2032                        // permission grants within these users.
2033                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2034                    }
2035                }
2036            }
2037
2038            // Log current value of "unknown sources" setting
2039            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2040                    getUnknownSourcesSettings());
2041
2042            // Remove the replaced package's older resources safely now
2043            // We delete after a gc for applications  on sdcard.
2044            if (res.removedInfo != null && res.removedInfo.args != null) {
2045                Runtime.getRuntime().gc();
2046                synchronized (mInstallLock) {
2047                    res.removedInfo.args.doPostDeleteLI(true);
2048                }
2049            } else {
2050                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2051                // and not block here.
2052                VMRuntime.getRuntime().requestConcurrentGC();
2053            }
2054
2055            // Notify DexManager that the package was installed for new users.
2056            // The updated users should already be indexed and the package code paths
2057            // should not change.
2058            // Don't notify the manager for ephemeral apps as they are not expected to
2059            // survive long enough to benefit of background optimizations.
2060            for (int userId : firstUsers) {
2061                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2062                // There's a race currently where some install events may interleave with an uninstall.
2063                // This can lead to package info being null (b/36642664).
2064                if (info != null) {
2065                    mDexManager.notifyPackageInstalled(info, userId);
2066                }
2067            }
2068        }
2069
2070        // If someone is watching installs - notify them
2071        if (installObserver != null) {
2072            try {
2073                Bundle extras = extrasForInstallResult(res);
2074                installObserver.onPackageInstalled(res.name, res.returnCode,
2075                        res.returnMsg, extras);
2076            } catch (RemoteException e) {
2077                Slog.i(TAG, "Observer no longer exists.");
2078            }
2079        }
2080    }
2081
2082    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2083            PackageParser.Package pkg) {
2084        if (pkg.parentPackage == null) {
2085            return;
2086        }
2087        if (pkg.requestedPermissions == null) {
2088            return;
2089        }
2090        final PackageSetting disabledSysParentPs = mSettings
2091                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2092        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2093                || !disabledSysParentPs.isPrivileged()
2094                || (disabledSysParentPs.childPackageNames != null
2095                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2096            return;
2097        }
2098        final int[] allUserIds = sUserManager.getUserIds();
2099        final int permCount = pkg.requestedPermissions.size();
2100        for (int i = 0; i < permCount; i++) {
2101            String permission = pkg.requestedPermissions.get(i);
2102            BasePermission bp = mSettings.mPermissions.get(permission);
2103            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2104                continue;
2105            }
2106            for (int userId : allUserIds) {
2107                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2108                        permission, userId)) {
2109                    grantRuntimePermission(pkg.packageName, permission, userId);
2110                }
2111            }
2112        }
2113    }
2114
2115    private StorageEventListener mStorageListener = new StorageEventListener() {
2116        @Override
2117        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2118            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2119                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2120                    final String volumeUuid = vol.getFsUuid();
2121
2122                    // Clean up any users or apps that were removed or recreated
2123                    // while this volume was missing
2124                    sUserManager.reconcileUsers(volumeUuid);
2125                    reconcileApps(volumeUuid);
2126
2127                    // Clean up any install sessions that expired or were
2128                    // cancelled while this volume was missing
2129                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2130
2131                    loadPrivatePackages(vol);
2132
2133                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2134                    unloadPrivatePackages(vol);
2135                }
2136            }
2137
2138            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2139                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2140                    updateExternalMediaStatus(true, false);
2141                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2142                    updateExternalMediaStatus(false, false);
2143                }
2144            }
2145        }
2146
2147        @Override
2148        public void onVolumeForgotten(String fsUuid) {
2149            if (TextUtils.isEmpty(fsUuid)) {
2150                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2151                return;
2152            }
2153
2154            // Remove any apps installed on the forgotten volume
2155            synchronized (mPackages) {
2156                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2157                for (PackageSetting ps : packages) {
2158                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2159                    deletePackageVersioned(new VersionedPackage(ps.name,
2160                            PackageManager.VERSION_CODE_HIGHEST),
2161                            new LegacyPackageDeleteObserver(null).getBinder(),
2162                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2163                    // Try very hard to release any references to this package
2164                    // so we don't risk the system server being killed due to
2165                    // open FDs
2166                    AttributeCache.instance().removePackage(ps.name);
2167                }
2168
2169                mSettings.onVolumeForgotten(fsUuid);
2170                mSettings.writeLPr();
2171            }
2172        }
2173    };
2174
2175    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2176            String[] grantedPermissions) {
2177        for (int userId : userIds) {
2178            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2179        }
2180    }
2181
2182    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2183            String[] grantedPermissions) {
2184        PackageSetting ps = (PackageSetting) pkg.mExtras;
2185        if (ps == null) {
2186            return;
2187        }
2188
2189        PermissionsState permissionsState = ps.getPermissionsState();
2190
2191        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2192                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2193
2194        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2195                >= Build.VERSION_CODES.M;
2196
2197        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2198
2199        for (String permission : pkg.requestedPermissions) {
2200            final BasePermission bp;
2201            synchronized (mPackages) {
2202                bp = mSettings.mPermissions.get(permission);
2203            }
2204            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2205                    && (!instantApp || bp.isInstant())
2206                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2207                    && (grantedPermissions == null
2208                           || ArrayUtils.contains(grantedPermissions, permission))) {
2209                final int flags = permissionsState.getPermissionFlags(permission, userId);
2210                if (supportsRuntimePermissions) {
2211                    // Installer cannot change immutable permissions.
2212                    if ((flags & immutableFlags) == 0) {
2213                        grantRuntimePermission(pkg.packageName, permission, userId);
2214                    }
2215                } else if (mPermissionReviewRequired) {
2216                    // In permission review mode we clear the review flag when we
2217                    // are asked to install the app with all permissions granted.
2218                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2219                        updatePermissionFlags(permission, pkg.packageName,
2220                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2221                    }
2222                }
2223            }
2224        }
2225    }
2226
2227    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2228        Bundle extras = null;
2229        switch (res.returnCode) {
2230            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2231                extras = new Bundle();
2232                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2233                        res.origPermission);
2234                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2235                        res.origPackage);
2236                break;
2237            }
2238            case PackageManager.INSTALL_SUCCEEDED: {
2239                extras = new Bundle();
2240                extras.putBoolean(Intent.EXTRA_REPLACING,
2241                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2242                break;
2243            }
2244        }
2245        return extras;
2246    }
2247
2248    void scheduleWriteSettingsLocked() {
2249        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2250            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2251        }
2252    }
2253
2254    void scheduleWritePackageListLocked(int userId) {
2255        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2256            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2257            msg.arg1 = userId;
2258            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2259        }
2260    }
2261
2262    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2263        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2264        scheduleWritePackageRestrictionsLocked(userId);
2265    }
2266
2267    void scheduleWritePackageRestrictionsLocked(int userId) {
2268        final int[] userIds = (userId == UserHandle.USER_ALL)
2269                ? sUserManager.getUserIds() : new int[]{userId};
2270        for (int nextUserId : userIds) {
2271            if (!sUserManager.exists(nextUserId)) return;
2272            mDirtyUsers.add(nextUserId);
2273            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2274                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2275            }
2276        }
2277    }
2278
2279    public static PackageManagerService main(Context context, Installer installer,
2280            boolean factoryTest, boolean onlyCore) {
2281        // Self-check for initial settings.
2282        PackageManagerServiceCompilerMapping.checkProperties();
2283
2284        PackageManagerService m = new PackageManagerService(context, installer,
2285                factoryTest, onlyCore);
2286        m.enableSystemUserPackages();
2287        ServiceManager.addService("package", m);
2288        return m;
2289    }
2290
2291    private void enableSystemUserPackages() {
2292        if (!UserManager.isSplitSystemUser()) {
2293            return;
2294        }
2295        // For system user, enable apps based on the following conditions:
2296        // - app is whitelisted or belong to one of these groups:
2297        //   -- system app which has no launcher icons
2298        //   -- system app which has INTERACT_ACROSS_USERS permission
2299        //   -- system IME app
2300        // - app is not in the blacklist
2301        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2302        Set<String> enableApps = new ArraySet<>();
2303        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2304                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2305                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2306        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2307        enableApps.addAll(wlApps);
2308        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2309                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2310        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2311        enableApps.removeAll(blApps);
2312        Log.i(TAG, "Applications installed for system user: " + enableApps);
2313        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2314                UserHandle.SYSTEM);
2315        final int allAppsSize = allAps.size();
2316        synchronized (mPackages) {
2317            for (int i = 0; i < allAppsSize; i++) {
2318                String pName = allAps.get(i);
2319                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2320                // Should not happen, but we shouldn't be failing if it does
2321                if (pkgSetting == null) {
2322                    continue;
2323                }
2324                boolean install = enableApps.contains(pName);
2325                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2326                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2327                            + " for system user");
2328                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2329                }
2330            }
2331            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2332        }
2333    }
2334
2335    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2336        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2337                Context.DISPLAY_SERVICE);
2338        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2339    }
2340
2341    /**
2342     * Requests that files preopted on a secondary system partition be copied to the data partition
2343     * if possible.  Note that the actual copying of the files is accomplished by init for security
2344     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2345     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2346     */
2347    private static void requestCopyPreoptedFiles() {
2348        final int WAIT_TIME_MS = 100;
2349        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2350        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2351            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2352            // We will wait for up to 100 seconds.
2353            final long timeStart = SystemClock.uptimeMillis();
2354            final long timeEnd = timeStart + 100 * 1000;
2355            long timeNow = timeStart;
2356            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2357                try {
2358                    Thread.sleep(WAIT_TIME_MS);
2359                } catch (InterruptedException e) {
2360                    // Do nothing
2361                }
2362                timeNow = SystemClock.uptimeMillis();
2363                if (timeNow > timeEnd) {
2364                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2365                    Slog.wtf(TAG, "cppreopt did not finish!");
2366                    break;
2367                }
2368            }
2369
2370            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2371        }
2372    }
2373
2374    public PackageManagerService(Context context, Installer installer,
2375            boolean factoryTest, boolean onlyCore) {
2376        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2377        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2378        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2379                SystemClock.uptimeMillis());
2380
2381        if (mSdkVersion <= 0) {
2382            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2383        }
2384
2385        mContext = context;
2386
2387        mPermissionReviewRequired = context.getResources().getBoolean(
2388                R.bool.config_permissionReviewRequired);
2389
2390        mFactoryTest = factoryTest;
2391        mOnlyCore = onlyCore;
2392        mMetrics = new DisplayMetrics();
2393        mSettings = new Settings(mPackages);
2394        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2395                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406
2407        String separateProcesses = SystemProperties.get("debug.separate_processes");
2408        if (separateProcesses != null && separateProcesses.length() > 0) {
2409            if ("*".equals(separateProcesses)) {
2410                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2411                mSeparateProcesses = null;
2412                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2413            } else {
2414                mDefParseFlags = 0;
2415                mSeparateProcesses = separateProcesses.split(",");
2416                Slog.w(TAG, "Running with debug.separate_processes: "
2417                        + separateProcesses);
2418            }
2419        } else {
2420            mDefParseFlags = 0;
2421            mSeparateProcesses = null;
2422        }
2423
2424        mInstaller = installer;
2425        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2426                "*dexopt*");
2427        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2428        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2429
2430        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2431                FgThread.get().getLooper());
2432
2433        getDefaultDisplayMetrics(context, mMetrics);
2434
2435        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2436        SystemConfig systemConfig = SystemConfig.getInstance();
2437        mGlobalGids = systemConfig.getGlobalGids();
2438        mSystemPermissions = systemConfig.getSystemPermissions();
2439        mAvailableFeatures = systemConfig.getAvailableFeatures();
2440        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2441
2442        mProtectedPackages = new ProtectedPackages(mContext);
2443
2444        synchronized (mInstallLock) {
2445        // writer
2446        synchronized (mPackages) {
2447            mHandlerThread = new ServiceThread(TAG,
2448                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2449            mHandlerThread.start();
2450            mHandler = new PackageHandler(mHandlerThread.getLooper());
2451            mProcessLoggingHandler = new ProcessLoggingHandler();
2452            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2453
2454            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2455            mInstantAppRegistry = new InstantAppRegistry(this);
2456
2457            File dataDir = Environment.getDataDirectory();
2458            mAppInstallDir = new File(dataDir, "app");
2459            mAppLib32InstallDir = new File(dataDir, "app-lib");
2460            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2461            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2462            sUserManager = new UserManagerService(context, this,
2463                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2464
2465            // Propagate permission configuration in to package manager.
2466            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2467                    = systemConfig.getPermissions();
2468            for (int i=0; i<permConfig.size(); i++) {
2469                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2470                BasePermission bp = mSettings.mPermissions.get(perm.name);
2471                if (bp == null) {
2472                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2473                    mSettings.mPermissions.put(perm.name, bp);
2474                }
2475                if (perm.gids != null) {
2476                    bp.setGids(perm.gids, perm.perUser);
2477                }
2478            }
2479
2480            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2481            final int builtInLibCount = libConfig.size();
2482            for (int i = 0; i < builtInLibCount; i++) {
2483                String name = libConfig.keyAt(i);
2484                String path = libConfig.valueAt(i);
2485                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2486                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2487            }
2488
2489            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2490
2491            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2492            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2493            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2494
2495            // Clean up orphaned packages for which the code path doesn't exist
2496            // and they are an update to a system app - caused by bug/32321269
2497            final int packageSettingCount = mSettings.mPackages.size();
2498            for (int i = packageSettingCount - 1; i >= 0; i--) {
2499                PackageSetting ps = mSettings.mPackages.valueAt(i);
2500                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2501                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2502                    mSettings.mPackages.removeAt(i);
2503                    mSettings.enableSystemPackageLPw(ps.name);
2504                }
2505            }
2506
2507            if (mFirstBoot) {
2508                requestCopyPreoptedFiles();
2509            }
2510
2511            String customResolverActivity = Resources.getSystem().getString(
2512                    R.string.config_customResolverActivity);
2513            if (TextUtils.isEmpty(customResolverActivity)) {
2514                customResolverActivity = null;
2515            } else {
2516                mCustomResolverComponentName = ComponentName.unflattenFromString(
2517                        customResolverActivity);
2518            }
2519
2520            long startTime = SystemClock.uptimeMillis();
2521
2522            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2523                    startTime);
2524
2525            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2526            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2527
2528            if (bootClassPath == null) {
2529                Slog.w(TAG, "No BOOTCLASSPATH found!");
2530            }
2531
2532            if (systemServerClassPath == null) {
2533                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2534            }
2535
2536            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2537
2538            final VersionInfo ver = mSettings.getInternalVersion();
2539            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2540            if (mIsUpgrade) {
2541                logCriticalInfo(Log.INFO,
2542                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2543            }
2544
2545            // when upgrading from pre-M, promote system app permissions from install to runtime
2546            mPromoteSystemApps =
2547                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2548
2549            // When upgrading from pre-N, we need to handle package extraction like first boot,
2550            // as there is no profiling data available.
2551            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2552
2553            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2554
2555            // save off the names of pre-existing system packages prior to scanning; we don't
2556            // want to automatically grant runtime permissions for new system apps
2557            if (mPromoteSystemApps) {
2558                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2559                while (pkgSettingIter.hasNext()) {
2560                    PackageSetting ps = pkgSettingIter.next();
2561                    if (isSystemApp(ps)) {
2562                        mExistingSystemPackages.add(ps.name);
2563                    }
2564                }
2565            }
2566
2567            mCacheDir = preparePackageParserCache(mIsUpgrade);
2568
2569            // Set flag to monitor and not change apk file paths when
2570            // scanning install directories.
2571            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2572
2573            if (mIsUpgrade || mFirstBoot) {
2574                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2575            }
2576
2577            // Collect vendor overlay packages. (Do this before scanning any apps.)
2578            // For security and version matching reason, only consider
2579            // overlay packages if they reside in the right directory.
2580            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2581                    | PackageParser.PARSE_IS_SYSTEM
2582                    | PackageParser.PARSE_IS_SYSTEM_DIR
2583                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2584
2585            mParallelPackageParserCallback.findStaticOverlayPackages();
2586
2587            // Find base frameworks (resource packages without code).
2588            scanDirTracedLI(frameworkDir, mDefParseFlags
2589                    | PackageParser.PARSE_IS_SYSTEM
2590                    | PackageParser.PARSE_IS_SYSTEM_DIR
2591                    | PackageParser.PARSE_IS_PRIVILEGED,
2592                    scanFlags | SCAN_NO_DEX, 0);
2593
2594            // Collected privileged system packages.
2595            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2596            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR
2599                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2600
2601            // Collect ordinary system packages.
2602            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603            scanDirTracedLI(systemAppDir, mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2606
2607            // Collect all vendor packages.
2608            File vendorAppDir = new File("/vendor/app");
2609            try {
2610                vendorAppDir = vendorAppDir.getCanonicalFile();
2611            } catch (IOException e) {
2612                // failed to look up canonical path, continue with original one
2613            }
2614            scanDirTracedLI(vendorAppDir, mDefParseFlags
2615                    | PackageParser.PARSE_IS_SYSTEM
2616                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2617
2618            // Collect all OEM packages.
2619            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2620            scanDirTracedLI(oemAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Prune any system packages that no longer exist.
2625            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2626            if (!mOnlyCore) {
2627                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2628                while (psit.hasNext()) {
2629                    PackageSetting ps = psit.next();
2630
2631                    /*
2632                     * If this is not a system app, it can't be a
2633                     * disable system app.
2634                     */
2635                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2636                        continue;
2637                    }
2638
2639                    /*
2640                     * If the package is scanned, it's not erased.
2641                     */
2642                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2643                    if (scannedPkg != null) {
2644                        /*
2645                         * If the system app is both scanned and in the
2646                         * disabled packages list, then it must have been
2647                         * added via OTA. Remove it from the currently
2648                         * scanned package so the previously user-installed
2649                         * application can be scanned.
2650                         */
2651                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2652                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2653                                    + ps.name + "; removing system app.  Last known codePath="
2654                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2655                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2656                                    + scannedPkg.mVersionCode);
2657                            removePackageLI(scannedPkg, true);
2658                            mExpectingBetter.put(ps.name, ps.codePath);
2659                        }
2660
2661                        continue;
2662                    }
2663
2664                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2665                        psit.remove();
2666                        logCriticalInfo(Log.WARN, "System package " + ps.name
2667                                + " no longer exists; it's data will be wiped");
2668                        // Actual deletion of code and data will be handled by later
2669                        // reconciliation step
2670                    } else {
2671                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2672                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2673                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2674                        }
2675                    }
2676                }
2677            }
2678
2679            //look for any incomplete package installations
2680            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2681            for (int i = 0; i < deletePkgsList.size(); i++) {
2682                // Actual deletion of code and data will be handled by later
2683                // reconciliation step
2684                final String packageName = deletePkgsList.get(i).name;
2685                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2686                synchronized (mPackages) {
2687                    mSettings.removePackageLPw(packageName);
2688                }
2689            }
2690
2691            //delete tmp files
2692            deleteTempPackageFiles();
2693
2694            // Remove any shared userIDs that have no associated packages
2695            mSettings.pruneSharedUsersLPw();
2696
2697            if (!mOnlyCore) {
2698                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2699                        SystemClock.uptimeMillis());
2700                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2701
2702                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2703                        | PackageParser.PARSE_FORWARD_LOCK,
2704                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2705
2706                /**
2707                 * Remove disable package settings for any updated system
2708                 * apps that were removed via an OTA. If they're not a
2709                 * previously-updated app, remove them completely.
2710                 * Otherwise, just revoke their system-level permissions.
2711                 */
2712                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2713                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2714                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2715
2716                    String msg;
2717                    if (deletedPkg == null) {
2718                        msg = "Updated system package " + deletedAppName
2719                                + " no longer exists; it's data will be wiped";
2720                        // Actual deletion of code and data will be handled by later
2721                        // reconciliation step
2722                    } else {
2723                        msg = "Updated system app + " + deletedAppName
2724                                + " no longer present; removing system privileges for "
2725                                + deletedAppName;
2726
2727                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2728
2729                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2730                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2731                    }
2732                    logCriticalInfo(Log.WARN, msg);
2733                }
2734
2735                /**
2736                 * Make sure all system apps that we expected to appear on
2737                 * the userdata partition actually showed up. If they never
2738                 * appeared, crawl back and revive the system version.
2739                 */
2740                for (int i = 0; i < mExpectingBetter.size(); i++) {
2741                    final String packageName = mExpectingBetter.keyAt(i);
2742                    if (!mPackages.containsKey(packageName)) {
2743                        final File scanFile = mExpectingBetter.valueAt(i);
2744
2745                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2746                                + " but never showed up; reverting to system");
2747
2748                        int reparseFlags = mDefParseFlags;
2749                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2750                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2751                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2752                                    | PackageParser.PARSE_IS_PRIVILEGED;
2753                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2754                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2755                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2756                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2759                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else {
2763                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2764                            continue;
2765                        }
2766
2767                        mSettings.enableSystemPackageLPw(packageName);
2768
2769                        try {
2770                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2771                        } catch (PackageManagerException e) {
2772                            Slog.e(TAG, "Failed to parse original system package: "
2773                                    + e.getMessage());
2774                        }
2775                    }
2776                }
2777            }
2778            mExpectingBetter.clear();
2779
2780            // Resolve the storage manager.
2781            mStorageManagerPackage = getStorageManagerPackageName();
2782
2783            // Resolve protected action filters. Only the setup wizard is allowed to
2784            // have a high priority filter for these actions.
2785            mSetupWizardPackage = getSetupWizardPackageName();
2786            if (mProtectedFilters.size() > 0) {
2787                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2788                    Slog.i(TAG, "No setup wizard;"
2789                        + " All protected intents capped to priority 0");
2790                }
2791                for (ActivityIntentInfo filter : mProtectedFilters) {
2792                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2793                        if (DEBUG_FILTERS) {
2794                            Slog.i(TAG, "Found setup wizard;"
2795                                + " allow priority " + filter.getPriority() + ";"
2796                                + " package: " + filter.activity.info.packageName
2797                                + " activity: " + filter.activity.className
2798                                + " priority: " + filter.getPriority());
2799                        }
2800                        // skip setup wizard; allow it to keep the high priority filter
2801                        continue;
2802                    }
2803                    if (DEBUG_FILTERS) {
2804                        Slog.i(TAG, "Protected action; cap priority to 0;"
2805                                + " package: " + filter.activity.info.packageName
2806                                + " activity: " + filter.activity.className
2807                                + " origPrio: " + filter.getPriority());
2808                    }
2809                    filter.setPriority(0);
2810                }
2811            }
2812            mDeferProtectedFilters = false;
2813            mProtectedFilters.clear();
2814
2815            // Now that we know all of the shared libraries, update all clients to have
2816            // the correct library paths.
2817            updateAllSharedLibrariesLPw(null);
2818
2819            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2820                // NOTE: We ignore potential failures here during a system scan (like
2821                // the rest of the commands above) because there's precious little we
2822                // can do about it. A settings error is reported, though.
2823                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2824            }
2825
2826            // Now that we know all the packages we are keeping,
2827            // read and update their last usage times.
2828            mPackageUsage.read(mPackages);
2829            mCompilerStats.read();
2830
2831            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2832                    SystemClock.uptimeMillis());
2833            Slog.i(TAG, "Time to scan packages: "
2834                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2835                    + " seconds");
2836
2837            // If the platform SDK has changed since the last time we booted,
2838            // we need to re-grant app permission to catch any new ones that
2839            // appear.  This is really a hack, and means that apps can in some
2840            // cases get permissions that the user didn't initially explicitly
2841            // allow...  it would be nice to have some better way to handle
2842            // this situation.
2843            int updateFlags = UPDATE_PERMISSIONS_ALL;
2844            if (ver.sdkVersion != mSdkVersion) {
2845                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2846                        + mSdkVersion + "; regranting permissions for internal storage");
2847                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2848            }
2849            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2850            ver.sdkVersion = mSdkVersion;
2851
2852            // If this is the first boot or an update from pre-M, and it is a normal
2853            // boot, then we need to initialize the default preferred apps across
2854            // all defined users.
2855            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2856                for (UserInfo user : sUserManager.getUsers(true)) {
2857                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2858                    applyFactoryDefaultBrowserLPw(user.id);
2859                    primeDomainVerificationsLPw(user.id);
2860                }
2861            }
2862
2863            // Prepare storage for system user really early during boot,
2864            // since core system apps like SettingsProvider and SystemUI
2865            // can't wait for user to start
2866            final int storageFlags;
2867            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2868                storageFlags = StorageManager.FLAG_STORAGE_DE;
2869            } else {
2870                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2871            }
2872            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2873                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2874                    true /* onlyCoreApps */);
2875            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2876                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2877                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2878                traceLog.traceBegin("AppDataFixup");
2879                try {
2880                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2881                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2882                } catch (InstallerException e) {
2883                    Slog.w(TAG, "Trouble fixing GIDs", e);
2884                }
2885                traceLog.traceEnd();
2886
2887                traceLog.traceBegin("AppDataPrepare");
2888                if (deferPackages == null || deferPackages.isEmpty()) {
2889                    return;
2890                }
2891                int count = 0;
2892                for (String pkgName : deferPackages) {
2893                    PackageParser.Package pkg = null;
2894                    synchronized (mPackages) {
2895                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2896                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2897                            pkg = ps.pkg;
2898                        }
2899                    }
2900                    if (pkg != null) {
2901                        synchronized (mInstallLock) {
2902                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2903                                    true /* maybeMigrateAppData */);
2904                        }
2905                        count++;
2906                    }
2907                }
2908                traceLog.traceEnd();
2909                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2910            }, "prepareAppData");
2911
2912            // If this is first boot after an OTA, and a normal boot, then
2913            // we need to clear code cache directories.
2914            // Note that we do *not* clear the application profiles. These remain valid
2915            // across OTAs and are used to drive profile verification (post OTA) and
2916            // profile compilation (without waiting to collect a fresh set of profiles).
2917            if (mIsUpgrade && !onlyCore) {
2918                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2919                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2920                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2921                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2922                        // No apps are running this early, so no need to freeze
2923                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2924                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2925                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2926                    }
2927                }
2928                ver.fingerprint = Build.FINGERPRINT;
2929            }
2930
2931            checkDefaultBrowser();
2932
2933            // clear only after permissions and other defaults have been updated
2934            mExistingSystemPackages.clear();
2935            mPromoteSystemApps = false;
2936
2937            // All the changes are done during package scanning.
2938            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2939
2940            // can downgrade to reader
2941            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2942            mSettings.writeLPr();
2943            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2944
2945            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2946                    SystemClock.uptimeMillis());
2947
2948            if (!mOnlyCore) {
2949                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2950                mRequiredInstallerPackage = getRequiredInstallerLPr();
2951                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2952                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2953                if (mIntentFilterVerifierComponent != null) {
2954                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2955                            mIntentFilterVerifierComponent);
2956                } else {
2957                    mIntentFilterVerifier = null;
2958                }
2959                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2960                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2961                        SharedLibraryInfo.VERSION_UNDEFINED);
2962                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2963                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2964                        SharedLibraryInfo.VERSION_UNDEFINED);
2965            } else {
2966                mRequiredVerifierPackage = null;
2967                mRequiredInstallerPackage = null;
2968                mRequiredUninstallerPackage = null;
2969                mIntentFilterVerifierComponent = null;
2970                mIntentFilterVerifier = null;
2971                mServicesSystemSharedLibraryPackageName = null;
2972                mSharedSystemSharedLibraryPackageName = null;
2973            }
2974
2975            mInstallerService = new PackageInstallerService(context, this);
2976            final Pair<ComponentName, String> instantAppResolverComponent =
2977                    getInstantAppResolverLPr();
2978            if (instantAppResolverComponent != null) {
2979                if (DEBUG_EPHEMERAL) {
2980                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2981                }
2982                mInstantAppResolverConnection = new EphemeralResolverConnection(
2983                        mContext, instantAppResolverComponent.first,
2984                        instantAppResolverComponent.second);
2985                mInstantAppResolverSettingsComponent =
2986                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2987            } else {
2988                mInstantAppResolverConnection = null;
2989                mInstantAppResolverSettingsComponent = null;
2990            }
2991            updateInstantAppInstallerLocked(null);
2992
2993            // Read and update the usage of dex files.
2994            // Do this at the end of PM init so that all the packages have their
2995            // data directory reconciled.
2996            // At this point we know the code paths of the packages, so we can validate
2997            // the disk file and build the internal cache.
2998            // The usage file is expected to be small so loading and verifying it
2999            // should take a fairly small time compare to the other activities (e.g. package
3000            // scanning).
3001            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3002            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3003            for (int userId : currentUserIds) {
3004                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3005            }
3006            mDexManager.load(userPackages);
3007        } // synchronized (mPackages)
3008        } // synchronized (mInstallLock)
3009
3010        // Now after opening every single application zip, make sure they
3011        // are all flushed.  Not really needed, but keeps things nice and
3012        // tidy.
3013        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3014        Runtime.getRuntime().gc();
3015        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3016
3017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3018        FallbackCategoryProvider.loadFallbacks();
3019        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3020
3021        // The initial scanning above does many calls into installd while
3022        // holding the mPackages lock, but we're mostly interested in yelling
3023        // once we have a booted system.
3024        mInstaller.setWarnIfHeld(mPackages);
3025
3026        // Expose private service for system components to use.
3027        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3028        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3029    }
3030
3031    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3032        // we're only interested in updating the installer appliction when 1) it's not
3033        // already set or 2) the modified package is the installer
3034        if (mInstantAppInstallerActivity != null
3035                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3036                        .equals(modifiedPackage)) {
3037            return;
3038        }
3039        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3040    }
3041
3042    private static File preparePackageParserCache(boolean isUpgrade) {
3043        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3044            return null;
3045        }
3046
3047        // Disable package parsing on eng builds to allow for faster incremental development.
3048        if ("eng".equals(Build.TYPE)) {
3049            return null;
3050        }
3051
3052        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3053            Slog.i(TAG, "Disabling package parser cache due to system property.");
3054            return null;
3055        }
3056
3057        // The base directory for the package parser cache lives under /data/system/.
3058        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3059                "package_cache");
3060        if (cacheBaseDir == null) {
3061            return null;
3062        }
3063
3064        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3065        // This also serves to "GC" unused entries when the package cache version changes (which
3066        // can only happen during upgrades).
3067        if (isUpgrade) {
3068            FileUtils.deleteContents(cacheBaseDir);
3069        }
3070
3071
3072        // Return the versioned package cache directory. This is something like
3073        // "/data/system/package_cache/1"
3074        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3075
3076        // The following is a workaround to aid development on non-numbered userdebug
3077        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3078        // the system partition is newer.
3079        //
3080        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3081        // that starts with "eng." to signify that this is an engineering build and not
3082        // destined for release.
3083        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3084            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3085
3086            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3087            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3088            // in general and should not be used for production changes. In this specific case,
3089            // we know that they will work.
3090            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3091            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3092                FileUtils.deleteContents(cacheBaseDir);
3093                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3094            }
3095        }
3096
3097        return cacheDir;
3098    }
3099
3100    @Override
3101    public boolean isFirstBoot() {
3102        // allow instant applications
3103        return mFirstBoot;
3104    }
3105
3106    @Override
3107    public boolean isOnlyCoreApps() {
3108        // allow instant applications
3109        return mOnlyCore;
3110    }
3111
3112    @Override
3113    public boolean isUpgrade() {
3114        // allow instant applications
3115        return mIsUpgrade;
3116    }
3117
3118    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3119        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3120
3121        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3122                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3123                UserHandle.USER_SYSTEM);
3124        if (matches.size() == 1) {
3125            return matches.get(0).getComponentInfo().packageName;
3126        } else if (matches.size() == 0) {
3127            Log.e(TAG, "There should probably be a verifier, but, none were found");
3128            return null;
3129        }
3130        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3131    }
3132
3133    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3134        synchronized (mPackages) {
3135            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3136            if (libraryEntry == null) {
3137                throw new IllegalStateException("Missing required shared library:" + name);
3138            }
3139            return libraryEntry.apk;
3140        }
3141    }
3142
3143    private @NonNull String getRequiredInstallerLPr() {
3144        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3145        intent.addCategory(Intent.CATEGORY_DEFAULT);
3146        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3147
3148        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3149                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3150                UserHandle.USER_SYSTEM);
3151        if (matches.size() == 1) {
3152            ResolveInfo resolveInfo = matches.get(0);
3153            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3154                throw new RuntimeException("The installer must be a privileged app");
3155            }
3156            return matches.get(0).getComponentInfo().packageName;
3157        } else {
3158            throw new RuntimeException("There must be exactly one installer; found " + matches);
3159        }
3160    }
3161
3162    private @NonNull String getRequiredUninstallerLPr() {
3163        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3164        intent.addCategory(Intent.CATEGORY_DEFAULT);
3165        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3166
3167        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3168                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3169                UserHandle.USER_SYSTEM);
3170        if (resolveInfo == null ||
3171                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3172            throw new RuntimeException("There must be exactly one uninstaller; found "
3173                    + resolveInfo);
3174        }
3175        return resolveInfo.getComponentInfo().packageName;
3176    }
3177
3178    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3179        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3180
3181        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3182                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3183                UserHandle.USER_SYSTEM);
3184        ResolveInfo best = null;
3185        final int N = matches.size();
3186        for (int i = 0; i < N; i++) {
3187            final ResolveInfo cur = matches.get(i);
3188            final String packageName = cur.getComponentInfo().packageName;
3189            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3190                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3191                continue;
3192            }
3193
3194            if (best == null || cur.priority > best.priority) {
3195                best = cur;
3196            }
3197        }
3198
3199        if (best != null) {
3200            return best.getComponentInfo().getComponentName();
3201        }
3202        Slog.w(TAG, "Intent filter verifier not found");
3203        return null;
3204    }
3205
3206    @Override
3207    public @Nullable ComponentName getInstantAppResolverComponent() {
3208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3209            return null;
3210        }
3211        synchronized (mPackages) {
3212            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3213            if (instantAppResolver == null) {
3214                return null;
3215            }
3216            return instantAppResolver.first;
3217        }
3218    }
3219
3220    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3221        final String[] packageArray =
3222                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3223        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3224            if (DEBUG_EPHEMERAL) {
3225                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3226            }
3227            return null;
3228        }
3229
3230        final int callingUid = Binder.getCallingUid();
3231        final int resolveFlags =
3232                MATCH_DIRECT_BOOT_AWARE
3233                | MATCH_DIRECT_BOOT_UNAWARE
3234                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3235        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3236        final Intent resolverIntent = new Intent(actionName);
3237        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3238                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3239        // temporarily look for the old action
3240        if (resolvers.size() == 0) {
3241            if (DEBUG_EPHEMERAL) {
3242                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3243            }
3244            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3245            resolverIntent.setAction(actionName);
3246            resolvers = queryIntentServicesInternal(resolverIntent, null,
3247                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3248        }
3249        final int N = resolvers.size();
3250        if (N == 0) {
3251            if (DEBUG_EPHEMERAL) {
3252                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3253            }
3254            return null;
3255        }
3256
3257        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3258        for (int i = 0; i < N; i++) {
3259            final ResolveInfo info = resolvers.get(i);
3260
3261            if (info.serviceInfo == null) {
3262                continue;
3263            }
3264
3265            final String packageName = info.serviceInfo.packageName;
3266            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3267                if (DEBUG_EPHEMERAL) {
3268                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3269                            + " pkg: " + packageName + ", info:" + info);
3270                }
3271                continue;
3272            }
3273
3274            if (DEBUG_EPHEMERAL) {
3275                Slog.v(TAG, "Ephemeral resolver found;"
3276                        + " pkg: " + packageName + ", info:" + info);
3277            }
3278            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3279        }
3280        if (DEBUG_EPHEMERAL) {
3281            Slog.v(TAG, "Ephemeral resolver NOT found");
3282        }
3283        return null;
3284    }
3285
3286    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3287        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3288        intent.addCategory(Intent.CATEGORY_DEFAULT);
3289        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3290
3291        final int resolveFlags =
3292                MATCH_DIRECT_BOOT_AWARE
3293                | MATCH_DIRECT_BOOT_UNAWARE
3294                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3295        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3296                resolveFlags, UserHandle.USER_SYSTEM);
3297        // temporarily look for the old action
3298        if (matches.isEmpty()) {
3299            if (DEBUG_EPHEMERAL) {
3300                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3301            }
3302            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3303            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3304                    resolveFlags, UserHandle.USER_SYSTEM);
3305        }
3306        Iterator<ResolveInfo> iter = matches.iterator();
3307        while (iter.hasNext()) {
3308            final ResolveInfo rInfo = iter.next();
3309            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3310            if (ps != null) {
3311                final PermissionsState permissionsState = ps.getPermissionsState();
3312                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3313                    continue;
3314                }
3315            }
3316            iter.remove();
3317        }
3318        if (matches.size() == 0) {
3319            return null;
3320        } else if (matches.size() == 1) {
3321            return (ActivityInfo) matches.get(0).getComponentInfo();
3322        } else {
3323            throw new RuntimeException(
3324                    "There must be at most one ephemeral installer; found " + matches);
3325        }
3326    }
3327
3328    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3329            @NonNull ComponentName resolver) {
3330        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3331                .addCategory(Intent.CATEGORY_DEFAULT)
3332                .setPackage(resolver.getPackageName());
3333        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3334        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3335                UserHandle.USER_SYSTEM);
3336        // temporarily look for the old action
3337        if (matches.isEmpty()) {
3338            if (DEBUG_EPHEMERAL) {
3339                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3340            }
3341            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3342            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3343                    UserHandle.USER_SYSTEM);
3344        }
3345        if (matches.isEmpty()) {
3346            return null;
3347        }
3348        return matches.get(0).getComponentInfo().getComponentName();
3349    }
3350
3351    private void primeDomainVerificationsLPw(int userId) {
3352        if (DEBUG_DOMAIN_VERIFICATION) {
3353            Slog.d(TAG, "Priming domain verifications in user " + userId);
3354        }
3355
3356        SystemConfig systemConfig = SystemConfig.getInstance();
3357        ArraySet<String> packages = systemConfig.getLinkedApps();
3358
3359        for (String packageName : packages) {
3360            PackageParser.Package pkg = mPackages.get(packageName);
3361            if (pkg != null) {
3362                if (!pkg.isSystemApp()) {
3363                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3364                    continue;
3365                }
3366
3367                ArraySet<String> domains = null;
3368                for (PackageParser.Activity a : pkg.activities) {
3369                    for (ActivityIntentInfo filter : a.intents) {
3370                        if (hasValidDomains(filter)) {
3371                            if (domains == null) {
3372                                domains = new ArraySet<String>();
3373                            }
3374                            domains.addAll(filter.getHostsList());
3375                        }
3376                    }
3377                }
3378
3379                if (domains != null && domains.size() > 0) {
3380                    if (DEBUG_DOMAIN_VERIFICATION) {
3381                        Slog.v(TAG, "      + " + packageName);
3382                    }
3383                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3384                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3385                    // and then 'always' in the per-user state actually used for intent resolution.
3386                    final IntentFilterVerificationInfo ivi;
3387                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3388                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3389                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3390                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3391                } else {
3392                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3393                            + "' does not handle web links");
3394                }
3395            } else {
3396                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3397            }
3398        }
3399
3400        scheduleWritePackageRestrictionsLocked(userId);
3401        scheduleWriteSettingsLocked();
3402    }
3403
3404    private void applyFactoryDefaultBrowserLPw(int userId) {
3405        // The default browser app's package name is stored in a string resource,
3406        // with a product-specific overlay used for vendor customization.
3407        String browserPkg = mContext.getResources().getString(
3408                com.android.internal.R.string.default_browser);
3409        if (!TextUtils.isEmpty(browserPkg)) {
3410            // non-empty string => required to be a known package
3411            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3412            if (ps == null) {
3413                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3414                browserPkg = null;
3415            } else {
3416                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3417            }
3418        }
3419
3420        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3421        // default.  If there's more than one, just leave everything alone.
3422        if (browserPkg == null) {
3423            calculateDefaultBrowserLPw(userId);
3424        }
3425    }
3426
3427    private void calculateDefaultBrowserLPw(int userId) {
3428        List<String> allBrowsers = resolveAllBrowserApps(userId);
3429        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3430        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3431    }
3432
3433    private List<String> resolveAllBrowserApps(int userId) {
3434        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3435        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3436                PackageManager.MATCH_ALL, userId);
3437
3438        final int count = list.size();
3439        List<String> result = new ArrayList<String>(count);
3440        for (int i=0; i<count; i++) {
3441            ResolveInfo info = list.get(i);
3442            if (info.activityInfo == null
3443                    || !info.handleAllWebDataURI
3444                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3445                    || result.contains(info.activityInfo.packageName)) {
3446                continue;
3447            }
3448            result.add(info.activityInfo.packageName);
3449        }
3450
3451        return result;
3452    }
3453
3454    private boolean packageIsBrowser(String packageName, int userId) {
3455        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3456                PackageManager.MATCH_ALL, userId);
3457        final int N = list.size();
3458        for (int i = 0; i < N; i++) {
3459            ResolveInfo info = list.get(i);
3460            if (packageName.equals(info.activityInfo.packageName)) {
3461                return true;
3462            }
3463        }
3464        return false;
3465    }
3466
3467    private void checkDefaultBrowser() {
3468        final int myUserId = UserHandle.myUserId();
3469        final String packageName = getDefaultBrowserPackageName(myUserId);
3470        if (packageName != null) {
3471            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3472            if (info == null) {
3473                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3474                synchronized (mPackages) {
3475                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3476                }
3477            }
3478        }
3479    }
3480
3481    @Override
3482    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3483            throws RemoteException {
3484        try {
3485            return super.onTransact(code, data, reply, flags);
3486        } catch (RuntimeException e) {
3487            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3488                Slog.wtf(TAG, "Package Manager Crash", e);
3489            }
3490            throw e;
3491        }
3492    }
3493
3494    static int[] appendInts(int[] cur, int[] add) {
3495        if (add == null) return cur;
3496        if (cur == null) return add;
3497        final int N = add.length;
3498        for (int i=0; i<N; i++) {
3499            cur = appendInt(cur, add[i]);
3500        }
3501        return cur;
3502    }
3503
3504    /**
3505     * Returns whether or not a full application can see an instant application.
3506     * <p>
3507     * Currently, there are three cases in which this can occur:
3508     * <ol>
3509     * <li>The calling application is a "special" process. The special
3510     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3511     *     and {@code 0}</li>
3512     * <li>The calling application has the permission
3513     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3514     * <li>The calling application is the default launcher on the
3515     *     system partition.</li>
3516     * </ol>
3517     */
3518    private boolean canViewInstantApps(int callingUid, int userId) {
3519        if (callingUid == Process.SYSTEM_UID
3520                || callingUid == Process.SHELL_UID
3521                || callingUid == Process.ROOT_UID) {
3522            return true;
3523        }
3524        if (mContext.checkCallingOrSelfPermission(
3525                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3526            return true;
3527        }
3528        if (mContext.checkCallingOrSelfPermission(
3529                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3530            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3531            if (homeComponent != null
3532                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3533                return true;
3534            }
3535        }
3536        return false;
3537    }
3538
3539    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3540        if (!sUserManager.exists(userId)) return null;
3541        if (ps == null) {
3542            return null;
3543        }
3544        PackageParser.Package p = ps.pkg;
3545        if (p == null) {
3546            return null;
3547        }
3548        final int callingUid = Binder.getCallingUid();
3549        // Filter out ephemeral app metadata:
3550        //   * The system/shell/root can see metadata for any app
3551        //   * An installed app can see metadata for 1) other installed apps
3552        //     and 2) ephemeral apps that have explicitly interacted with it
3553        //   * Ephemeral apps can only see their own data and exposed installed apps
3554        //   * Holding a signature permission allows seeing instant apps
3555        if (filterAppAccessLPr(ps, callingUid, userId)) {
3556            return null;
3557        }
3558
3559        final PermissionsState permissionsState = ps.getPermissionsState();
3560
3561        // Compute GIDs only if requested
3562        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3563                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3564        // Compute granted permissions only if package has requested permissions
3565        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3566                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3567        final PackageUserState state = ps.readUserState(userId);
3568
3569        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3570                && ps.isSystem()) {
3571            flags |= MATCH_ANY_USER;
3572        }
3573
3574        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3575                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3576
3577        if (packageInfo == null) {
3578            return null;
3579        }
3580
3581        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3582                resolveExternalPackageNameLPr(p);
3583
3584        return packageInfo;
3585    }
3586
3587    @Override
3588    public void checkPackageStartable(String packageName, int userId) {
3589        final int callingUid = Binder.getCallingUid();
3590        if (getInstantAppPackageName(callingUid) != null) {
3591            throw new SecurityException("Instant applications don't have access to this method");
3592        }
3593        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3594        synchronized (mPackages) {
3595            final PackageSetting ps = mSettings.mPackages.get(packageName);
3596            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3597                throw new SecurityException("Package " + packageName + " was not found!");
3598            }
3599
3600            if (!ps.getInstalled(userId)) {
3601                throw new SecurityException(
3602                        "Package " + packageName + " was not installed for user " + userId + "!");
3603            }
3604
3605            if (mSafeMode && !ps.isSystem()) {
3606                throw new SecurityException("Package " + packageName + " not a system app!");
3607            }
3608
3609            if (mFrozenPackages.contains(packageName)) {
3610                throw new SecurityException("Package " + packageName + " is currently frozen!");
3611            }
3612
3613            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3614                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3615                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3616            }
3617        }
3618    }
3619
3620    @Override
3621    public boolean isPackageAvailable(String packageName, int userId) {
3622        if (!sUserManager.exists(userId)) return false;
3623        final int callingUid = Binder.getCallingUid();
3624        enforceCrossUserPermission(callingUid, userId,
3625                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3626        synchronized (mPackages) {
3627            PackageParser.Package p = mPackages.get(packageName);
3628            if (p != null) {
3629                final PackageSetting ps = (PackageSetting) p.mExtras;
3630                if (filterAppAccessLPr(ps, callingUid, userId)) {
3631                    return false;
3632                }
3633                if (ps != null) {
3634                    final PackageUserState state = ps.readUserState(userId);
3635                    if (state != null) {
3636                        return PackageParser.isAvailable(state);
3637                    }
3638                }
3639            }
3640        }
3641        return false;
3642    }
3643
3644    @Override
3645    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3646        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3647                flags, Binder.getCallingUid(), userId);
3648    }
3649
3650    @Override
3651    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3652            int flags, int userId) {
3653        return getPackageInfoInternal(versionedPackage.getPackageName(),
3654                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3655    }
3656
3657    /**
3658     * Important: The provided filterCallingUid is used exclusively to filter out packages
3659     * that can be seen based on user state. It's typically the original caller uid prior
3660     * to clearing. Because it can only be provided by trusted code, it's value can be
3661     * trusted and will be used as-is; unlike userId which will be validated by this method.
3662     */
3663    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3664            int flags, int filterCallingUid, int userId) {
3665        if (!sUserManager.exists(userId)) return null;
3666        flags = updateFlagsForPackage(flags, userId, packageName);
3667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3668                false /* requireFullPermission */, false /* checkShell */, "get package info");
3669
3670        // reader
3671        synchronized (mPackages) {
3672            // Normalize package name to handle renamed packages and static libs
3673            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3674
3675            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3676            if (matchFactoryOnly) {
3677                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3678                if (ps != null) {
3679                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3680                        return null;
3681                    }
3682                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3683                        return null;
3684                    }
3685                    return generatePackageInfo(ps, flags, userId);
3686                }
3687            }
3688
3689            PackageParser.Package p = mPackages.get(packageName);
3690            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3691                return null;
3692            }
3693            if (DEBUG_PACKAGE_INFO)
3694                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3695            if (p != null) {
3696                final PackageSetting ps = (PackageSetting) p.mExtras;
3697                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3698                    return null;
3699                }
3700                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3701                    return null;
3702                }
3703                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3704            }
3705            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3706                final PackageSetting ps = mSettings.mPackages.get(packageName);
3707                if (ps == null) return null;
3708                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3709                    return null;
3710                }
3711                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3712                    return null;
3713                }
3714                return generatePackageInfo(ps, flags, userId);
3715            }
3716        }
3717        return null;
3718    }
3719
3720    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3721        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3722            return true;
3723        }
3724        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3725            return true;
3726        }
3727        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3728            return true;
3729        }
3730        return false;
3731    }
3732
3733    private boolean isComponentVisibleToInstantApp(
3734            @Nullable ComponentName component, @ComponentType int type) {
3735        if (type == TYPE_ACTIVITY) {
3736            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3737            return activity != null
3738                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3739                    : false;
3740        } else if (type == TYPE_RECEIVER) {
3741            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_SERVICE) {
3746            final PackageParser.Service service = mServices.mServices.get(component);
3747            return service != null
3748                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_PROVIDER) {
3751            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3752            return provider != null
3753                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_UNKNOWN) {
3756            return isComponentVisibleToInstantApp(component);
3757        }
3758        return false;
3759    }
3760
3761    /**
3762     * Returns whether or not access to the application should be filtered.
3763     * <p>
3764     * Access may be limited based upon whether the calling or target applications
3765     * are instant applications.
3766     *
3767     * @see #canAccessInstantApps(int)
3768     */
3769    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3770            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3771        // if we're in an isolated process, get the real calling UID
3772        if (Process.isIsolated(callingUid)) {
3773            callingUid = mIsolatedOwners.get(callingUid);
3774        }
3775        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3776        final boolean callerIsInstantApp = instantAppPkgName != null;
3777        if (ps == null) {
3778            if (callerIsInstantApp) {
3779                // pretend the application exists, but, needs to be filtered
3780                return true;
3781            }
3782            return false;
3783        }
3784        // if the target and caller are the same application, don't filter
3785        if (isCallerSameApp(ps.name, callingUid)) {
3786            return false;
3787        }
3788        if (callerIsInstantApp) {
3789            // request for a specific component; if it hasn't been explicitly exposed, filter
3790            if (component != null) {
3791                return !isComponentVisibleToInstantApp(component, componentType);
3792            }
3793            // request for application; if no components have been explicitly exposed, filter
3794            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3795        }
3796        if (ps.getInstantApp(userId)) {
3797            // caller can see all components of all instant applications, don't filter
3798            if (canViewInstantApps(callingUid, userId)) {
3799                return false;
3800            }
3801            // request for a specific instant application component, filter
3802            if (component != null) {
3803                return true;
3804            }
3805            // request for an instant application; if the caller hasn't been granted access, filter
3806            return !mInstantAppRegistry.isInstantAccessGranted(
3807                    userId, UserHandle.getAppId(callingUid), ps.appId);
3808        }
3809        return false;
3810    }
3811
3812    /**
3813     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3814     */
3815    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3816        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3817    }
3818
3819    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3820            int flags) {
3821        // Callers can access only the libs they depend on, otherwise they need to explicitly
3822        // ask for the shared libraries given the caller is allowed to access all static libs.
3823        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3824            // System/shell/root get to see all static libs
3825            final int appId = UserHandle.getAppId(uid);
3826            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3827                    || appId == Process.ROOT_UID) {
3828                return false;
3829            }
3830        }
3831
3832        // No package means no static lib as it is always on internal storage
3833        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3834            return false;
3835        }
3836
3837        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3838                ps.pkg.staticSharedLibVersion);
3839        if (libEntry == null) {
3840            return false;
3841        }
3842
3843        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3844        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3845        if (uidPackageNames == null) {
3846            return true;
3847        }
3848
3849        for (String uidPackageName : uidPackageNames) {
3850            if (ps.name.equals(uidPackageName)) {
3851                return false;
3852            }
3853            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3854            if (uidPs != null) {
3855                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3856                        libEntry.info.getName());
3857                if (index < 0) {
3858                    continue;
3859                }
3860                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3861                    return false;
3862                }
3863            }
3864        }
3865        return true;
3866    }
3867
3868    @Override
3869    public String[] currentToCanonicalPackageNames(String[] names) {
3870        final int callingUid = Binder.getCallingUid();
3871        if (getInstantAppPackageName(callingUid) != null) {
3872            return names;
3873        }
3874        final String[] out = new String[names.length];
3875        // reader
3876        synchronized (mPackages) {
3877            final int callingUserId = UserHandle.getUserId(callingUid);
3878            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3879            for (int i=names.length-1; i>=0; i--) {
3880                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3881                boolean translateName = false;
3882                if (ps != null && ps.realName != null) {
3883                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3884                    translateName = !targetIsInstantApp
3885                            || canViewInstantApps
3886                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3887                                    UserHandle.getAppId(callingUid), ps.appId);
3888                }
3889                out[i] = translateName ? ps.realName : names[i];
3890            }
3891        }
3892        return out;
3893    }
3894
3895    @Override
3896    public String[] canonicalToCurrentPackageNames(String[] names) {
3897        final int callingUid = Binder.getCallingUid();
3898        if (getInstantAppPackageName(callingUid) != null) {
3899            return names;
3900        }
3901        final String[] out = new String[names.length];
3902        // reader
3903        synchronized (mPackages) {
3904            final int callingUserId = UserHandle.getUserId(callingUid);
3905            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3906            for (int i=names.length-1; i>=0; i--) {
3907                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3908                boolean translateName = false;
3909                if (cur != null) {
3910                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3911                    final boolean targetIsInstantApp =
3912                            ps != null && ps.getInstantApp(callingUserId);
3913                    translateName = !targetIsInstantApp
3914                            || canViewInstantApps
3915                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3916                                    UserHandle.getAppId(callingUid), ps.appId);
3917                }
3918                out[i] = translateName ? cur : names[i];
3919            }
3920        }
3921        return out;
3922    }
3923
3924    @Override
3925    public int getPackageUid(String packageName, int flags, int userId) {
3926        if (!sUserManager.exists(userId)) return -1;
3927        final int callingUid = Binder.getCallingUid();
3928        flags = updateFlagsForPackage(flags, userId, packageName);
3929        enforceCrossUserPermission(callingUid, userId,
3930                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3931
3932        // reader
3933        synchronized (mPackages) {
3934            final PackageParser.Package p = mPackages.get(packageName);
3935            if (p != null && p.isMatch(flags)) {
3936                PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterAppAccessLPr(ps, callingUid, userId)) {
3938                    return -1;
3939                }
3940                return UserHandle.getUid(userId, p.applicationInfo.uid);
3941            }
3942            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3943                final PackageSetting ps = mSettings.mPackages.get(packageName);
3944                if (ps != null && ps.isMatch(flags)
3945                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3946                    return UserHandle.getUid(userId, ps.appId);
3947                }
3948            }
3949        }
3950
3951        return -1;
3952    }
3953
3954    @Override
3955    public int[] getPackageGids(String packageName, int flags, int userId) {
3956        if (!sUserManager.exists(userId)) return null;
3957        final int callingUid = Binder.getCallingUid();
3958        flags = updateFlagsForPackage(flags, userId, packageName);
3959        enforceCrossUserPermission(callingUid, userId,
3960                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3961
3962        // reader
3963        synchronized (mPackages) {
3964            final PackageParser.Package p = mPackages.get(packageName);
3965            if (p != null && p.isMatch(flags)) {
3966                PackageSetting ps = (PackageSetting) p.mExtras;
3967                if (filterAppAccessLPr(ps, callingUid, userId)) {
3968                    return null;
3969                }
3970                // TODO: Shouldn't this be checking for package installed state for userId and
3971                // return null?
3972                return ps.getPermissionsState().computeGids(userId);
3973            }
3974            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3975                final PackageSetting ps = mSettings.mPackages.get(packageName);
3976                if (ps != null && ps.isMatch(flags)
3977                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3978                    return ps.getPermissionsState().computeGids(userId);
3979                }
3980            }
3981        }
3982
3983        return null;
3984    }
3985
3986    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3987        if (bp.perm != null) {
3988            return PackageParser.generatePermissionInfo(bp.perm, flags);
3989        }
3990        PermissionInfo pi = new PermissionInfo();
3991        pi.name = bp.name;
3992        pi.packageName = bp.sourcePackage;
3993        pi.nonLocalizedLabel = bp.name;
3994        pi.protectionLevel = bp.protectionLevel;
3995        return pi;
3996    }
3997
3998    @Override
3999    public PermissionInfo getPermissionInfo(String name, int flags) {
4000        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4001            return null;
4002        }
4003        // reader
4004        synchronized (mPackages) {
4005            final BasePermission p = mSettings.mPermissions.get(name);
4006            if (p != null) {
4007                return generatePermissionInfo(p, flags);
4008            }
4009            return null;
4010        }
4011    }
4012
4013    @Override
4014    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4015            int flags) {
4016        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4017            return null;
4018        }
4019        // reader
4020        synchronized (mPackages) {
4021            if (group != null && !mPermissionGroups.containsKey(group)) {
4022                // This is thrown as NameNotFoundException
4023                return null;
4024            }
4025
4026            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4027            for (BasePermission p : mSettings.mPermissions.values()) {
4028                if (group == null) {
4029                    if (p.perm == null || p.perm.info.group == null) {
4030                        out.add(generatePermissionInfo(p, flags));
4031                    }
4032                } else {
4033                    if (p.perm != null && group.equals(p.perm.info.group)) {
4034                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4035                    }
4036                }
4037            }
4038            return new ParceledListSlice<>(out);
4039        }
4040    }
4041
4042    @Override
4043    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4044        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4045            return null;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            return PackageParser.generatePermissionGroupInfo(
4050                    mPermissionGroups.get(name), flags);
4051        }
4052    }
4053
4054    @Override
4055    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4056        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4057            return ParceledListSlice.emptyList();
4058        }
4059        // reader
4060        synchronized (mPackages) {
4061            final int N = mPermissionGroups.size();
4062            ArrayList<PermissionGroupInfo> out
4063                    = new ArrayList<PermissionGroupInfo>(N);
4064            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4065                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4066            }
4067            return new ParceledListSlice<>(out);
4068        }
4069    }
4070
4071    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4072            int filterCallingUid, int userId) {
4073        if (!sUserManager.exists(userId)) return null;
4074        PackageSetting ps = mSettings.mPackages.get(packageName);
4075        if (ps != null) {
4076            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4077                return null;
4078            }
4079            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4080                return null;
4081            }
4082            if (ps.pkg == null) {
4083                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4084                if (pInfo != null) {
4085                    return pInfo.applicationInfo;
4086                }
4087                return null;
4088            }
4089            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4090                    ps.readUserState(userId), userId);
4091            if (ai != null) {
4092                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4093            }
4094            return ai;
4095        }
4096        return null;
4097    }
4098
4099    @Override
4100    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4101        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4102    }
4103
4104    /**
4105     * Important: The provided filterCallingUid is used exclusively to filter out applications
4106     * that can be seen based on user state. It's typically the original caller uid prior
4107     * to clearing. Because it can only be provided by trusted code, it's value can be
4108     * trusted and will be used as-is; unlike userId which will be validated by this method.
4109     */
4110    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4111            int filterCallingUid, int userId) {
4112        if (!sUserManager.exists(userId)) return null;
4113        flags = updateFlagsForApplication(flags, userId, packageName);
4114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4115                false /* requireFullPermission */, false /* checkShell */, "get application info");
4116
4117        // writer
4118        synchronized (mPackages) {
4119            // Normalize package name to handle renamed packages and static libs
4120            packageName = resolveInternalPackageNameLPr(packageName,
4121                    PackageManager.VERSION_CODE_HIGHEST);
4122
4123            PackageParser.Package p = mPackages.get(packageName);
4124            if (DEBUG_PACKAGE_INFO) Log.v(
4125                    TAG, "getApplicationInfo " + packageName
4126                    + ": " + p);
4127            if (p != null) {
4128                PackageSetting ps = mSettings.mPackages.get(packageName);
4129                if (ps == null) return null;
4130                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4131                    return null;
4132                }
4133                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4134                    return null;
4135                }
4136                // Note: isEnabledLP() does not apply here - always return info
4137                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4138                        p, flags, ps.readUserState(userId), userId);
4139                if (ai != null) {
4140                    ai.packageName = resolveExternalPackageNameLPr(p);
4141                }
4142                return ai;
4143            }
4144            if ("android".equals(packageName)||"system".equals(packageName)) {
4145                return mAndroidApplication;
4146            }
4147            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4148                // Already generates the external package name
4149                return generateApplicationInfoFromSettingsLPw(packageName,
4150                        flags, filterCallingUid, userId);
4151            }
4152        }
4153        return null;
4154    }
4155
4156    private String normalizePackageNameLPr(String packageName) {
4157        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4158        return normalizedPackageName != null ? normalizedPackageName : packageName;
4159    }
4160
4161    @Override
4162    public void deletePreloadsFileCache() {
4163        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4164            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4165        }
4166        File dir = Environment.getDataPreloadsFileCacheDirectory();
4167        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4168        FileUtils.deleteContents(dir);
4169    }
4170
4171    @Override
4172    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4173            final int storageFlags, final IPackageDataObserver observer) {
4174        mContext.enforceCallingOrSelfPermission(
4175                android.Manifest.permission.CLEAR_APP_CACHE, null);
4176        mHandler.post(() -> {
4177            boolean success = false;
4178            try {
4179                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4180                success = true;
4181            } catch (IOException e) {
4182                Slog.w(TAG, e);
4183            }
4184            if (observer != null) {
4185                try {
4186                    observer.onRemoveCompleted(null, success);
4187                } catch (RemoteException e) {
4188                    Slog.w(TAG, e);
4189                }
4190            }
4191        });
4192    }
4193
4194    @Override
4195    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4196            final int storageFlags, final IntentSender pi) {
4197        mContext.enforceCallingOrSelfPermission(
4198                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4199        mHandler.post(() -> {
4200            boolean success = false;
4201            try {
4202                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4203                success = true;
4204            } catch (IOException e) {
4205                Slog.w(TAG, e);
4206            }
4207            if (pi != null) {
4208                try {
4209                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4210                } catch (SendIntentException e) {
4211                    Slog.w(TAG, e);
4212                }
4213            }
4214        });
4215    }
4216
4217    /**
4218     * Blocking call to clear various types of cached data across the system
4219     * until the requested bytes are available.
4220     */
4221    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4222        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4223        final File file = storage.findPathForUuid(volumeUuid);
4224        if (file.getUsableSpace() >= bytes) return;
4225
4226        if (ENABLE_FREE_CACHE_V2) {
4227            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4228                    volumeUuid);
4229            final boolean aggressive = (storageFlags
4230                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4231            final boolean defyReserved = (storageFlags
4232                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4233            final long reservedBytes = (aggressive || defyReserved) ? 0
4234                    : storage.getStorageCacheBytes(file);
4235
4236            // 1. Pre-flight to determine if we have any chance to succeed
4237            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4238            if (internalVolume && (aggressive || SystemProperties
4239                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4240                deletePreloadsFileCache();
4241                if (file.getUsableSpace() >= bytes) return;
4242            }
4243
4244            // 3. Consider parsed APK data (aggressive only)
4245            if (internalVolume && aggressive) {
4246                FileUtils.deleteContents(mCacheDir);
4247                if (file.getUsableSpace() >= bytes) return;
4248            }
4249
4250            // 4. Consider cached app data (above quotas)
4251            try {
4252                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4253                        Installer.FLAG_FREE_CACHE_V2);
4254            } catch (InstallerException ignored) {
4255            }
4256            if (file.getUsableSpace() >= bytes) return;
4257
4258            // 5. Consider shared libraries with refcount=0 and age>min cache period
4259            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4260                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4261                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4262                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4263                return;
4264            }
4265
4266            // 6. Consider dexopt output (aggressive only)
4267            // TODO: Implement
4268
4269            // 7. Consider installed instant apps unused longer than min cache period
4270            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4271                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4272                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4273                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4274                return;
4275            }
4276
4277            // 8. Consider cached app data (below quotas)
4278            try {
4279                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4280                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4281            } catch (InstallerException ignored) {
4282            }
4283            if (file.getUsableSpace() >= bytes) return;
4284
4285            // 9. Consider DropBox entries
4286            // TODO: Implement
4287
4288            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4289            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4290                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4291                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4292                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4293                return;
4294            }
4295        } else {
4296            try {
4297                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4298            } catch (InstallerException ignored) {
4299            }
4300            if (file.getUsableSpace() >= bytes) return;
4301        }
4302
4303        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4304    }
4305
4306    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4307            throws IOException {
4308        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4309        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4310
4311        List<VersionedPackage> packagesToDelete = null;
4312        final long now = System.currentTimeMillis();
4313
4314        synchronized (mPackages) {
4315            final int[] allUsers = sUserManager.getUserIds();
4316            final int libCount = mSharedLibraries.size();
4317            for (int i = 0; i < libCount; i++) {
4318                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4319                if (versionedLib == null) {
4320                    continue;
4321                }
4322                final int versionCount = versionedLib.size();
4323                for (int j = 0; j < versionCount; j++) {
4324                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4325                    // Skip packages that are not static shared libs.
4326                    if (!libInfo.isStatic()) {
4327                        break;
4328                    }
4329                    // Important: We skip static shared libs used for some user since
4330                    // in such a case we need to keep the APK on the device. The check for
4331                    // a lib being used for any user is performed by the uninstall call.
4332                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4333                    // Resolve the package name - we use synthetic package names internally
4334                    final String internalPackageName = resolveInternalPackageNameLPr(
4335                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4336                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4337                    // Skip unused static shared libs cached less than the min period
4338                    // to prevent pruning a lib needed by a subsequently installed package.
4339                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4340                        continue;
4341                    }
4342                    if (packagesToDelete == null) {
4343                        packagesToDelete = new ArrayList<>();
4344                    }
4345                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4346                            declaringPackage.getVersionCode()));
4347                }
4348            }
4349        }
4350
4351        if (packagesToDelete != null) {
4352            final int packageCount = packagesToDelete.size();
4353            for (int i = 0; i < packageCount; i++) {
4354                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4355                // Delete the package synchronously (will fail of the lib used for any user).
4356                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4357                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4358                                == PackageManager.DELETE_SUCCEEDED) {
4359                    if (volume.getUsableSpace() >= neededSpace) {
4360                        return true;
4361                    }
4362                }
4363            }
4364        }
4365
4366        return false;
4367    }
4368
4369    /**
4370     * Update given flags based on encryption status of current user.
4371     */
4372    private int updateFlags(int flags, int userId) {
4373        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4374                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4375            // Caller expressed an explicit opinion about what encryption
4376            // aware/unaware components they want to see, so fall through and
4377            // give them what they want
4378        } else {
4379            // Caller expressed no opinion, so match based on user state
4380            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4381                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4382            } else {
4383                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4384            }
4385        }
4386        return flags;
4387    }
4388
4389    private UserManagerInternal getUserManagerInternal() {
4390        if (mUserManagerInternal == null) {
4391            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4392        }
4393        return mUserManagerInternal;
4394    }
4395
4396    private DeviceIdleController.LocalService getDeviceIdleController() {
4397        if (mDeviceIdleController == null) {
4398            mDeviceIdleController =
4399                    LocalServices.getService(DeviceIdleController.LocalService.class);
4400        }
4401        return mDeviceIdleController;
4402    }
4403
4404    /**
4405     * Update given flags when being used to request {@link PackageInfo}.
4406     */
4407    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4408        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4409        boolean triaged = true;
4410        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4411                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4412            // Caller is asking for component details, so they'd better be
4413            // asking for specific encryption matching behavior, or be triaged
4414            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4415                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4416                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4417                triaged = false;
4418            }
4419        }
4420        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4421                | PackageManager.MATCH_SYSTEM_ONLY
4422                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4423            triaged = false;
4424        }
4425        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4426            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4427                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4428                    + Debug.getCallers(5));
4429        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4430                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4431            // If the caller wants all packages and has a restricted profile associated with it,
4432            // then match all users. This is to make sure that launchers that need to access work
4433            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4434            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4435            flags |= PackageManager.MATCH_ANY_USER;
4436        }
4437        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4438            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4439                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4440        }
4441        return updateFlags(flags, userId);
4442    }
4443
4444    /**
4445     * Update given flags when being used to request {@link ApplicationInfo}.
4446     */
4447    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4448        return updateFlagsForPackage(flags, userId, cookie);
4449    }
4450
4451    /**
4452     * Update given flags when being used to request {@link ComponentInfo}.
4453     */
4454    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4455        if (cookie instanceof Intent) {
4456            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4457                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4458            }
4459        }
4460
4461        boolean triaged = true;
4462        // Caller is asking for component details, so they'd better be
4463        // asking for specific encryption matching behavior, or be triaged
4464        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4465                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4466                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4467            triaged = false;
4468        }
4469        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4470            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4471                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4472        }
4473
4474        return updateFlags(flags, userId);
4475    }
4476
4477    /**
4478     * Update given intent when being used to request {@link ResolveInfo}.
4479     */
4480    private Intent updateIntentForResolve(Intent intent) {
4481        if (intent.getSelector() != null) {
4482            intent = intent.getSelector();
4483        }
4484        if (DEBUG_PREFERRED) {
4485            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4486        }
4487        return intent;
4488    }
4489
4490    /**
4491     * Update given flags when being used to request {@link ResolveInfo}.
4492     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4493     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4494     * flag set. However, this flag is only honoured in three circumstances:
4495     * <ul>
4496     * <li>when called from a system process</li>
4497     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4498     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4499     * action and a {@code android.intent.category.BROWSABLE} category</li>
4500     * </ul>
4501     */
4502    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4503        return updateFlagsForResolve(flags, userId, intent, callingUid,
4504                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4505    }
4506    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4507            boolean wantInstantApps) {
4508        return updateFlagsForResolve(flags, userId, intent, callingUid,
4509                wantInstantApps, false /*onlyExposedExplicitly*/);
4510    }
4511    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4512            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4513        // Safe mode means we shouldn't match any third-party components
4514        if (mSafeMode) {
4515            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4516        }
4517        if (getInstantAppPackageName(callingUid) != null) {
4518            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4519            if (onlyExposedExplicitly) {
4520                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4521            }
4522            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4523            flags |= PackageManager.MATCH_INSTANT;
4524        } else {
4525            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4526            final boolean allowMatchInstant =
4527                    (wantInstantApps
4528                            && Intent.ACTION_VIEW.equals(intent.getAction())
4529                            && hasWebURI(intent))
4530                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4531            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4532                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4533            if (!allowMatchInstant) {
4534                flags &= ~PackageManager.MATCH_INSTANT;
4535            }
4536        }
4537        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4538    }
4539
4540    @Override
4541    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4542        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4543    }
4544
4545    /**
4546     * Important: The provided filterCallingUid is used exclusively to filter out activities
4547     * that can be seen based on user state. It's typically the original caller uid prior
4548     * to clearing. Because it can only be provided by trusted code, it's value can be
4549     * trusted and will be used as-is; unlike userId which will be validated by this method.
4550     */
4551    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4552            int filterCallingUid, int userId) {
4553        if (!sUserManager.exists(userId)) return null;
4554        flags = updateFlagsForComponent(flags, userId, component);
4555        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4556                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4557        synchronized (mPackages) {
4558            PackageParser.Activity a = mActivities.mActivities.get(component);
4559
4560            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4561            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4562                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4563                if (ps == null) return null;
4564                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4565                    return null;
4566                }
4567                return PackageParser.generateActivityInfo(
4568                        a, flags, ps.readUserState(userId), userId);
4569            }
4570            if (mResolveComponentName.equals(component)) {
4571                return PackageParser.generateActivityInfo(
4572                        mResolveActivity, flags, new PackageUserState(), userId);
4573            }
4574        }
4575        return null;
4576    }
4577
4578    @Override
4579    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4580            String resolvedType) {
4581        synchronized (mPackages) {
4582            if (component.equals(mResolveComponentName)) {
4583                // The resolver supports EVERYTHING!
4584                return true;
4585            }
4586            final int callingUid = Binder.getCallingUid();
4587            final int callingUserId = UserHandle.getUserId(callingUid);
4588            PackageParser.Activity a = mActivities.mActivities.get(component);
4589            if (a == null) {
4590                return false;
4591            }
4592            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4593            if (ps == null) {
4594                return false;
4595            }
4596            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4597                return false;
4598            }
4599            for (int i=0; i<a.intents.size(); i++) {
4600                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4601                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4602                    return true;
4603                }
4604            }
4605            return false;
4606        }
4607    }
4608
4609    @Override
4610    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4611        if (!sUserManager.exists(userId)) return null;
4612        final int callingUid = Binder.getCallingUid();
4613        flags = updateFlagsForComponent(flags, userId, component);
4614        enforceCrossUserPermission(callingUid, userId,
4615                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4616        synchronized (mPackages) {
4617            PackageParser.Activity a = mReceivers.mActivities.get(component);
4618            if (DEBUG_PACKAGE_INFO) Log.v(
4619                TAG, "getReceiverInfo " + component + ": " + a);
4620            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4622                if (ps == null) return null;
4623                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4624                    return null;
4625                }
4626                return PackageParser.generateActivityInfo(
4627                        a, flags, ps.readUserState(userId), userId);
4628            }
4629        }
4630        return null;
4631    }
4632
4633    @Override
4634    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4635            int flags, int userId) {
4636        if (!sUserManager.exists(userId)) return null;
4637        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4638        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4639            return null;
4640        }
4641
4642        flags = updateFlagsForPackage(flags, userId, null);
4643
4644        final boolean canSeeStaticLibraries =
4645                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4646                        == PERMISSION_GRANTED
4647                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4648                        == PERMISSION_GRANTED
4649                || canRequestPackageInstallsInternal(packageName,
4650                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4651                        false  /* throwIfPermNotDeclared*/)
4652                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4653                        == PERMISSION_GRANTED;
4654
4655        synchronized (mPackages) {
4656            List<SharedLibraryInfo> result = null;
4657
4658            final int libCount = mSharedLibraries.size();
4659            for (int i = 0; i < libCount; i++) {
4660                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4661                if (versionedLib == null) {
4662                    continue;
4663                }
4664
4665                final int versionCount = versionedLib.size();
4666                for (int j = 0; j < versionCount; j++) {
4667                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4668                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4669                        break;
4670                    }
4671                    final long identity = Binder.clearCallingIdentity();
4672                    try {
4673                        PackageInfo packageInfo = getPackageInfoVersioned(
4674                                libInfo.getDeclaringPackage(), flags
4675                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4676                        if (packageInfo == null) {
4677                            continue;
4678                        }
4679                    } finally {
4680                        Binder.restoreCallingIdentity(identity);
4681                    }
4682
4683                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4684                            libInfo.getVersion(), libInfo.getType(),
4685                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4686                            flags, userId));
4687
4688                    if (result == null) {
4689                        result = new ArrayList<>();
4690                    }
4691                    result.add(resLibInfo);
4692                }
4693            }
4694
4695            return result != null ? new ParceledListSlice<>(result) : null;
4696        }
4697    }
4698
4699    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4700            SharedLibraryInfo libInfo, int flags, int userId) {
4701        List<VersionedPackage> versionedPackages = null;
4702        final int packageCount = mSettings.mPackages.size();
4703        for (int i = 0; i < packageCount; i++) {
4704            PackageSetting ps = mSettings.mPackages.valueAt(i);
4705
4706            if (ps == null) {
4707                continue;
4708            }
4709
4710            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4711                continue;
4712            }
4713
4714            final String libName = libInfo.getName();
4715            if (libInfo.isStatic()) {
4716                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4717                if (libIdx < 0) {
4718                    continue;
4719                }
4720                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4721                    continue;
4722                }
4723                if (versionedPackages == null) {
4724                    versionedPackages = new ArrayList<>();
4725                }
4726                // If the dependent is a static shared lib, use the public package name
4727                String dependentPackageName = ps.name;
4728                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4729                    dependentPackageName = ps.pkg.manifestPackageName;
4730                }
4731                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4732            } else if (ps.pkg != null) {
4733                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4734                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4735                    if (versionedPackages == null) {
4736                        versionedPackages = new ArrayList<>();
4737                    }
4738                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4739                }
4740            }
4741        }
4742
4743        return versionedPackages;
4744    }
4745
4746    @Override
4747    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4748        if (!sUserManager.exists(userId)) return null;
4749        final int callingUid = Binder.getCallingUid();
4750        flags = updateFlagsForComponent(flags, userId, component);
4751        enforceCrossUserPermission(callingUid, userId,
4752                false /* requireFullPermission */, false /* checkShell */, "get service info");
4753        synchronized (mPackages) {
4754            PackageParser.Service s = mServices.mServices.get(component);
4755            if (DEBUG_PACKAGE_INFO) Log.v(
4756                TAG, "getServiceInfo " + component + ": " + s);
4757            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4758                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4759                if (ps == null) return null;
4760                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4761                    return null;
4762                }
4763                return PackageParser.generateServiceInfo(
4764                        s, flags, ps.readUserState(userId), userId);
4765            }
4766        }
4767        return null;
4768    }
4769
4770    @Override
4771    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4772        if (!sUserManager.exists(userId)) return null;
4773        final int callingUid = Binder.getCallingUid();
4774        flags = updateFlagsForComponent(flags, userId, component);
4775        enforceCrossUserPermission(callingUid, userId,
4776                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4777        synchronized (mPackages) {
4778            PackageParser.Provider p = mProviders.mProviders.get(component);
4779            if (DEBUG_PACKAGE_INFO) Log.v(
4780                TAG, "getProviderInfo " + component + ": " + p);
4781            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4782                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4783                if (ps == null) return null;
4784                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4785                    return null;
4786                }
4787                return PackageParser.generateProviderInfo(
4788                        p, flags, ps.readUserState(userId), userId);
4789            }
4790        }
4791        return null;
4792    }
4793
4794    @Override
4795    public String[] getSystemSharedLibraryNames() {
4796        // allow instant applications
4797        synchronized (mPackages) {
4798            Set<String> libs = null;
4799            final int libCount = mSharedLibraries.size();
4800            for (int i = 0; i < libCount; i++) {
4801                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4802                if (versionedLib == null) {
4803                    continue;
4804                }
4805                final int versionCount = versionedLib.size();
4806                for (int j = 0; j < versionCount; j++) {
4807                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4808                    if (!libEntry.info.isStatic()) {
4809                        if (libs == null) {
4810                            libs = new ArraySet<>();
4811                        }
4812                        libs.add(libEntry.info.getName());
4813                        break;
4814                    }
4815                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4816                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4817                            UserHandle.getUserId(Binder.getCallingUid()),
4818                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4819                        if (libs == null) {
4820                            libs = new ArraySet<>();
4821                        }
4822                        libs.add(libEntry.info.getName());
4823                        break;
4824                    }
4825                }
4826            }
4827
4828            if (libs != null) {
4829                String[] libsArray = new String[libs.size()];
4830                libs.toArray(libsArray);
4831                return libsArray;
4832            }
4833
4834            return null;
4835        }
4836    }
4837
4838    @Override
4839    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4840        // allow instant applications
4841        synchronized (mPackages) {
4842            return mServicesSystemSharedLibraryPackageName;
4843        }
4844    }
4845
4846    @Override
4847    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4848        // allow instant applications
4849        synchronized (mPackages) {
4850            return mSharedSystemSharedLibraryPackageName;
4851        }
4852    }
4853
4854    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4855        for (int i = userList.length - 1; i >= 0; --i) {
4856            final int userId = userList[i];
4857            // don't add instant app to the list of updates
4858            if (pkgSetting.getInstantApp(userId)) {
4859                continue;
4860            }
4861            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4862            if (changedPackages == null) {
4863                changedPackages = new SparseArray<>();
4864                mChangedPackages.put(userId, changedPackages);
4865            }
4866            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4867            if (sequenceNumbers == null) {
4868                sequenceNumbers = new HashMap<>();
4869                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4870            }
4871            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4872            if (sequenceNumber != null) {
4873                changedPackages.remove(sequenceNumber);
4874            }
4875            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4876            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4877        }
4878        mChangedPackagesSequenceNumber++;
4879    }
4880
4881    @Override
4882    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4883        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4884            return null;
4885        }
4886        synchronized (mPackages) {
4887            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4888                return null;
4889            }
4890            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4891            if (changedPackages == null) {
4892                return null;
4893            }
4894            final List<String> packageNames =
4895                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4896            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4897                final String packageName = changedPackages.get(i);
4898                if (packageName != null) {
4899                    packageNames.add(packageName);
4900                }
4901            }
4902            return packageNames.isEmpty()
4903                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4904        }
4905    }
4906
4907    @Override
4908    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4909        // allow instant applications
4910        ArrayList<FeatureInfo> res;
4911        synchronized (mAvailableFeatures) {
4912            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4913            res.addAll(mAvailableFeatures.values());
4914        }
4915        final FeatureInfo fi = new FeatureInfo();
4916        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4917                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4918        res.add(fi);
4919
4920        return new ParceledListSlice<>(res);
4921    }
4922
4923    @Override
4924    public boolean hasSystemFeature(String name, int version) {
4925        // allow instant applications
4926        synchronized (mAvailableFeatures) {
4927            final FeatureInfo feat = mAvailableFeatures.get(name);
4928            if (feat == null) {
4929                return false;
4930            } else {
4931                return feat.version >= version;
4932            }
4933        }
4934    }
4935
4936    @Override
4937    public int checkPermission(String permName, String pkgName, int userId) {
4938        if (!sUserManager.exists(userId)) {
4939            return PackageManager.PERMISSION_DENIED;
4940        }
4941        final int callingUid = Binder.getCallingUid();
4942
4943        synchronized (mPackages) {
4944            final PackageParser.Package p = mPackages.get(pkgName);
4945            if (p != null && p.mExtras != null) {
4946                final PackageSetting ps = (PackageSetting) p.mExtras;
4947                if (filterAppAccessLPr(ps, callingUid, userId)) {
4948                    return PackageManager.PERMISSION_DENIED;
4949                }
4950                final boolean instantApp = ps.getInstantApp(userId);
4951                final PermissionsState permissionsState = ps.getPermissionsState();
4952                if (permissionsState.hasPermission(permName, userId)) {
4953                    if (instantApp) {
4954                        BasePermission bp = mSettings.mPermissions.get(permName);
4955                        if (bp != null && bp.isInstant()) {
4956                            return PackageManager.PERMISSION_GRANTED;
4957                        }
4958                    } else {
4959                        return PackageManager.PERMISSION_GRANTED;
4960                    }
4961                }
4962                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4963                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4964                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4965                    return PackageManager.PERMISSION_GRANTED;
4966                }
4967            }
4968        }
4969
4970        return PackageManager.PERMISSION_DENIED;
4971    }
4972
4973    @Override
4974    public int checkUidPermission(String permName, int uid) {
4975        final int callingUid = Binder.getCallingUid();
4976        final int callingUserId = UserHandle.getUserId(callingUid);
4977        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4978        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4979        final int userId = UserHandle.getUserId(uid);
4980        if (!sUserManager.exists(userId)) {
4981            return PackageManager.PERMISSION_DENIED;
4982        }
4983
4984        synchronized (mPackages) {
4985            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4986            if (obj != null) {
4987                if (obj instanceof SharedUserSetting) {
4988                    if (isCallerInstantApp) {
4989                        return PackageManager.PERMISSION_DENIED;
4990                    }
4991                } else if (obj instanceof PackageSetting) {
4992                    final PackageSetting ps = (PackageSetting) obj;
4993                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4994                        return PackageManager.PERMISSION_DENIED;
4995                    }
4996                }
4997                final SettingBase settingBase = (SettingBase) obj;
4998                final PermissionsState permissionsState = settingBase.getPermissionsState();
4999                if (permissionsState.hasPermission(permName, userId)) {
5000                    if (isUidInstantApp) {
5001                        BasePermission bp = mSettings.mPermissions.get(permName);
5002                        if (bp != null && bp.isInstant()) {
5003                            return PackageManager.PERMISSION_GRANTED;
5004                        }
5005                    } else {
5006                        return PackageManager.PERMISSION_GRANTED;
5007                    }
5008                }
5009                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5010                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5011                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5012                    return PackageManager.PERMISSION_GRANTED;
5013                }
5014            } else {
5015                ArraySet<String> perms = mSystemPermissions.get(uid);
5016                if (perms != null) {
5017                    if (perms.contains(permName)) {
5018                        return PackageManager.PERMISSION_GRANTED;
5019                    }
5020                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5021                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5022                        return PackageManager.PERMISSION_GRANTED;
5023                    }
5024                }
5025            }
5026        }
5027
5028        return PackageManager.PERMISSION_DENIED;
5029    }
5030
5031    @Override
5032    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5033        if (UserHandle.getCallingUserId() != userId) {
5034            mContext.enforceCallingPermission(
5035                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5036                    "isPermissionRevokedByPolicy for user " + userId);
5037        }
5038
5039        if (checkPermission(permission, packageName, userId)
5040                == PackageManager.PERMISSION_GRANTED) {
5041            return false;
5042        }
5043
5044        final int callingUid = Binder.getCallingUid();
5045        if (getInstantAppPackageName(callingUid) != null) {
5046            if (!isCallerSameApp(packageName, callingUid)) {
5047                return false;
5048            }
5049        } else {
5050            if (isInstantApp(packageName, userId)) {
5051                return false;
5052            }
5053        }
5054
5055        final long identity = Binder.clearCallingIdentity();
5056        try {
5057            final int flags = getPermissionFlags(permission, packageName, userId);
5058            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5059        } finally {
5060            Binder.restoreCallingIdentity(identity);
5061        }
5062    }
5063
5064    @Override
5065    public String getPermissionControllerPackageName() {
5066        synchronized (mPackages) {
5067            return mRequiredInstallerPackage;
5068        }
5069    }
5070
5071    /**
5072     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5073     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5074     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5075     * @param message the message to log on security exception
5076     */
5077    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5078            boolean checkShell, String message) {
5079        if (userId < 0) {
5080            throw new IllegalArgumentException("Invalid userId " + userId);
5081        }
5082        if (checkShell) {
5083            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5084        }
5085        if (userId == UserHandle.getUserId(callingUid)) return;
5086        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5087            if (requireFullPermission) {
5088                mContext.enforceCallingOrSelfPermission(
5089                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5090            } else {
5091                try {
5092                    mContext.enforceCallingOrSelfPermission(
5093                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5094                } catch (SecurityException se) {
5095                    mContext.enforceCallingOrSelfPermission(
5096                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5097                }
5098            }
5099        }
5100    }
5101
5102    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5103        if (callingUid == Process.SHELL_UID) {
5104            if (userHandle >= 0
5105                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5106                throw new SecurityException("Shell does not have permission to access user "
5107                        + userHandle);
5108            } else if (userHandle < 0) {
5109                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5110                        + Debug.getCallers(3));
5111            }
5112        }
5113    }
5114
5115    private BasePermission findPermissionTreeLP(String permName) {
5116        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5117            if (permName.startsWith(bp.name) &&
5118                    permName.length() > bp.name.length() &&
5119                    permName.charAt(bp.name.length()) == '.') {
5120                return bp;
5121            }
5122        }
5123        return null;
5124    }
5125
5126    private BasePermission checkPermissionTreeLP(String permName) {
5127        if (permName != null) {
5128            BasePermission bp = findPermissionTreeLP(permName);
5129            if (bp != null) {
5130                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5131                    return bp;
5132                }
5133                throw new SecurityException("Calling uid "
5134                        + Binder.getCallingUid()
5135                        + " is not allowed to add to permission tree "
5136                        + bp.name + " owned by uid " + bp.uid);
5137            }
5138        }
5139        throw new SecurityException("No permission tree found for " + permName);
5140    }
5141
5142    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5143        if (s1 == null) {
5144            return s2 == null;
5145        }
5146        if (s2 == null) {
5147            return false;
5148        }
5149        if (s1.getClass() != s2.getClass()) {
5150            return false;
5151        }
5152        return s1.equals(s2);
5153    }
5154
5155    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5156        if (pi1.icon != pi2.icon) return false;
5157        if (pi1.logo != pi2.logo) return false;
5158        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5159        if (!compareStrings(pi1.name, pi2.name)) return false;
5160        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5161        // We'll take care of setting this one.
5162        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5163        // These are not currently stored in settings.
5164        //if (!compareStrings(pi1.group, pi2.group)) return false;
5165        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5166        //if (pi1.labelRes != pi2.labelRes) return false;
5167        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5168        return true;
5169    }
5170
5171    int permissionInfoFootprint(PermissionInfo info) {
5172        int size = info.name.length();
5173        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5174        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5175        return size;
5176    }
5177
5178    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5179        int size = 0;
5180        for (BasePermission perm : mSettings.mPermissions.values()) {
5181            if (perm.uid == tree.uid) {
5182                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5183            }
5184        }
5185        return size;
5186    }
5187
5188    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5189        // We calculate the max size of permissions defined by this uid and throw
5190        // if that plus the size of 'info' would exceed our stated maximum.
5191        if (tree.uid != Process.SYSTEM_UID) {
5192            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5193            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5194                throw new SecurityException("Permission tree size cap exceeded");
5195            }
5196        }
5197    }
5198
5199    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5200        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5201            throw new SecurityException("Instant apps can't add permissions");
5202        }
5203        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5204            throw new SecurityException("Label must be specified in permission");
5205        }
5206        BasePermission tree = checkPermissionTreeLP(info.name);
5207        BasePermission bp = mSettings.mPermissions.get(info.name);
5208        boolean added = bp == null;
5209        boolean changed = true;
5210        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5211        if (added) {
5212            enforcePermissionCapLocked(info, tree);
5213            bp = new BasePermission(info.name, tree.sourcePackage,
5214                    BasePermission.TYPE_DYNAMIC);
5215        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5216            throw new SecurityException(
5217                    "Not allowed to modify non-dynamic permission "
5218                    + info.name);
5219        } else {
5220            if (bp.protectionLevel == fixedLevel
5221                    && bp.perm.owner.equals(tree.perm.owner)
5222                    && bp.uid == tree.uid
5223                    && comparePermissionInfos(bp.perm.info, info)) {
5224                changed = false;
5225            }
5226        }
5227        bp.protectionLevel = fixedLevel;
5228        info = new PermissionInfo(info);
5229        info.protectionLevel = fixedLevel;
5230        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5231        bp.perm.info.packageName = tree.perm.info.packageName;
5232        bp.uid = tree.uid;
5233        if (added) {
5234            mSettings.mPermissions.put(info.name, bp);
5235        }
5236        if (changed) {
5237            if (!async) {
5238                mSettings.writeLPr();
5239            } else {
5240                scheduleWriteSettingsLocked();
5241            }
5242        }
5243        return added;
5244    }
5245
5246    @Override
5247    public boolean addPermission(PermissionInfo info) {
5248        synchronized (mPackages) {
5249            return addPermissionLocked(info, false);
5250        }
5251    }
5252
5253    @Override
5254    public boolean addPermissionAsync(PermissionInfo info) {
5255        synchronized (mPackages) {
5256            return addPermissionLocked(info, true);
5257        }
5258    }
5259
5260    @Override
5261    public void removePermission(String name) {
5262        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5263            throw new SecurityException("Instant applications don't have access to this method");
5264        }
5265        synchronized (mPackages) {
5266            checkPermissionTreeLP(name);
5267            BasePermission bp = mSettings.mPermissions.get(name);
5268            if (bp != null) {
5269                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5270                    throw new SecurityException(
5271                            "Not allowed to modify non-dynamic permission "
5272                            + name);
5273                }
5274                mSettings.mPermissions.remove(name);
5275                mSettings.writeLPr();
5276            }
5277        }
5278    }
5279
5280    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5281            PackageParser.Package pkg, BasePermission bp) {
5282        int index = pkg.requestedPermissions.indexOf(bp.name);
5283        if (index == -1) {
5284            throw new SecurityException("Package " + pkg.packageName
5285                    + " has not requested permission " + bp.name);
5286        }
5287        if (!bp.isRuntime() && !bp.isDevelopment()) {
5288            throw new SecurityException("Permission " + bp.name
5289                    + " is not a changeable permission type");
5290        }
5291    }
5292
5293    @Override
5294    public void grantRuntimePermission(String packageName, String name, final int userId) {
5295        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5296    }
5297
5298    private void grantRuntimePermission(String packageName, String name, final int userId,
5299            boolean overridePolicy) {
5300        if (!sUserManager.exists(userId)) {
5301            Log.e(TAG, "No such user:" + userId);
5302            return;
5303        }
5304        final int callingUid = Binder.getCallingUid();
5305
5306        mContext.enforceCallingOrSelfPermission(
5307                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5308                "grantRuntimePermission");
5309
5310        enforceCrossUserPermission(callingUid, userId,
5311                true /* requireFullPermission */, true /* checkShell */,
5312                "grantRuntimePermission");
5313
5314        final int uid;
5315        final PackageSetting ps;
5316
5317        synchronized (mPackages) {
5318            final PackageParser.Package pkg = mPackages.get(packageName);
5319            if (pkg == null) {
5320                throw new IllegalArgumentException("Unknown package: " + packageName);
5321            }
5322            final BasePermission bp = mSettings.mPermissions.get(name);
5323            if (bp == null) {
5324                throw new IllegalArgumentException("Unknown permission: " + name);
5325            }
5326            ps = (PackageSetting) pkg.mExtras;
5327            if (ps == null
5328                    || filterAppAccessLPr(ps, callingUid, userId)) {
5329                throw new IllegalArgumentException("Unknown package: " + packageName);
5330            }
5331
5332            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5333
5334            // If a permission review is required for legacy apps we represent
5335            // their permissions as always granted runtime ones since we need
5336            // to keep the review required permission flag per user while an
5337            // install permission's state is shared across all users.
5338            if (mPermissionReviewRequired
5339                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5340                    && bp.isRuntime()) {
5341                return;
5342            }
5343
5344            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5345
5346            final PermissionsState permissionsState = ps.getPermissionsState();
5347
5348            final int flags = permissionsState.getPermissionFlags(name, userId);
5349            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5350                throw new SecurityException("Cannot grant system fixed permission "
5351                        + name + " for package " + packageName);
5352            }
5353            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5354                throw new SecurityException("Cannot grant policy fixed permission "
5355                        + name + " for package " + packageName);
5356            }
5357
5358            if (bp.isDevelopment()) {
5359                // Development permissions must be handled specially, since they are not
5360                // normal runtime permissions.  For now they apply to all users.
5361                if (permissionsState.grantInstallPermission(bp) !=
5362                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5363                    scheduleWriteSettingsLocked();
5364                }
5365                return;
5366            }
5367
5368            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5369                throw new SecurityException("Cannot grant non-ephemeral permission"
5370                        + name + " for package " + packageName);
5371            }
5372
5373            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5374                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5375                return;
5376            }
5377
5378            final int result = permissionsState.grantRuntimePermission(bp, userId);
5379            switch (result) {
5380                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5381                    return;
5382                }
5383
5384                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5385                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5386                    mHandler.post(new Runnable() {
5387                        @Override
5388                        public void run() {
5389                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5390                        }
5391                    });
5392                }
5393                break;
5394            }
5395
5396            if (bp.isRuntime()) {
5397                logPermissionGranted(mContext, name, packageName);
5398            }
5399
5400            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5401
5402            // Not critical if that is lost - app has to request again.
5403            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5404        }
5405
5406        // Only need to do this if user is initialized. Otherwise it's a new user
5407        // and there are no processes running as the user yet and there's no need
5408        // to make an expensive call to remount processes for the changed permissions.
5409        if (READ_EXTERNAL_STORAGE.equals(name)
5410                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5411            final long token = Binder.clearCallingIdentity();
5412            try {
5413                if (sUserManager.isInitialized(userId)) {
5414                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5415                            StorageManagerInternal.class);
5416                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5417                }
5418            } finally {
5419                Binder.restoreCallingIdentity(token);
5420            }
5421        }
5422    }
5423
5424    @Override
5425    public void revokeRuntimePermission(String packageName, String name, int userId) {
5426        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5427    }
5428
5429    private void revokeRuntimePermission(String packageName, String name, int userId,
5430            boolean overridePolicy) {
5431        if (!sUserManager.exists(userId)) {
5432            Log.e(TAG, "No such user:" + userId);
5433            return;
5434        }
5435
5436        mContext.enforceCallingOrSelfPermission(
5437                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5438                "revokeRuntimePermission");
5439
5440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5441                true /* requireFullPermission */, true /* checkShell */,
5442                "revokeRuntimePermission");
5443
5444        final int appId;
5445
5446        synchronized (mPackages) {
5447            final PackageParser.Package pkg = mPackages.get(packageName);
5448            if (pkg == null) {
5449                throw new IllegalArgumentException("Unknown package: " + packageName);
5450            }
5451            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5452            if (ps == null
5453                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5454                throw new IllegalArgumentException("Unknown package: " + packageName);
5455            }
5456            final BasePermission bp = mSettings.mPermissions.get(name);
5457            if (bp == null) {
5458                throw new IllegalArgumentException("Unknown permission: " + name);
5459            }
5460
5461            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5462
5463            // If a permission review is required for legacy apps we represent
5464            // their permissions as always granted runtime ones since we need
5465            // to keep the review required permission flag per user while an
5466            // install permission's state is shared across all users.
5467            if (mPermissionReviewRequired
5468                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5469                    && bp.isRuntime()) {
5470                return;
5471            }
5472
5473            final PermissionsState permissionsState = ps.getPermissionsState();
5474
5475            final int flags = permissionsState.getPermissionFlags(name, userId);
5476            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5477                throw new SecurityException("Cannot revoke system fixed permission "
5478                        + name + " for package " + packageName);
5479            }
5480            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5481                throw new SecurityException("Cannot revoke policy fixed permission "
5482                        + name + " for package " + packageName);
5483            }
5484
5485            if (bp.isDevelopment()) {
5486                // Development permissions must be handled specially, since they are not
5487                // normal runtime permissions.  For now they apply to all users.
5488                if (permissionsState.revokeInstallPermission(bp) !=
5489                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5490                    scheduleWriteSettingsLocked();
5491                }
5492                return;
5493            }
5494
5495            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5496                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5497                return;
5498            }
5499
5500            if (bp.isRuntime()) {
5501                logPermissionRevoked(mContext, name, packageName);
5502            }
5503
5504            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5505
5506            // Critical, after this call app should never have the permission.
5507            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5508
5509            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5510        }
5511
5512        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5513    }
5514
5515    /**
5516     * Get the first event id for the permission.
5517     *
5518     * <p>There are four events for each permission: <ul>
5519     *     <li>Request permission: first id + 0</li>
5520     *     <li>Grant permission: first id + 1</li>
5521     *     <li>Request for permission denied: first id + 2</li>
5522     *     <li>Revoke permission: first id + 3</li>
5523     * </ul></p>
5524     *
5525     * @param name name of the permission
5526     *
5527     * @return The first event id for the permission
5528     */
5529    private static int getBaseEventId(@NonNull String name) {
5530        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5531
5532        if (eventIdIndex == -1) {
5533            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5534                    || "user".equals(Build.TYPE)) {
5535                Log.i(TAG, "Unknown permission " + name);
5536
5537                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5538            } else {
5539                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5540                //
5541                // Also update
5542                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5543                // - metrics_constants.proto
5544                throw new IllegalStateException("Unknown permission " + name);
5545            }
5546        }
5547
5548        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5549    }
5550
5551    /**
5552     * Log that a permission was revoked.
5553     *
5554     * @param context Context of the caller
5555     * @param name name of the permission
5556     * @param packageName package permission if for
5557     */
5558    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5559            @NonNull String packageName) {
5560        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5561    }
5562
5563    /**
5564     * Log that a permission request was granted.
5565     *
5566     * @param context Context of the caller
5567     * @param name name of the permission
5568     * @param packageName package permission if for
5569     */
5570    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5571            @NonNull String packageName) {
5572        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5573    }
5574
5575    @Override
5576    public void resetRuntimePermissions() {
5577        mContext.enforceCallingOrSelfPermission(
5578                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5579                "revokeRuntimePermission");
5580
5581        int callingUid = Binder.getCallingUid();
5582        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5583            mContext.enforceCallingOrSelfPermission(
5584                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5585                    "resetRuntimePermissions");
5586        }
5587
5588        synchronized (mPackages) {
5589            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5590            for (int userId : UserManagerService.getInstance().getUserIds()) {
5591                final int packageCount = mPackages.size();
5592                for (int i = 0; i < packageCount; i++) {
5593                    PackageParser.Package pkg = mPackages.valueAt(i);
5594                    if (!(pkg.mExtras instanceof PackageSetting)) {
5595                        continue;
5596                    }
5597                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5598                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5599                }
5600            }
5601        }
5602    }
5603
5604    @Override
5605    public int getPermissionFlags(String name, String packageName, int userId) {
5606        if (!sUserManager.exists(userId)) {
5607            return 0;
5608        }
5609
5610        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5611
5612        final int callingUid = Binder.getCallingUid();
5613        enforceCrossUserPermission(callingUid, userId,
5614                true /* requireFullPermission */, false /* checkShell */,
5615                "getPermissionFlags");
5616
5617        synchronized (mPackages) {
5618            final PackageParser.Package pkg = mPackages.get(packageName);
5619            if (pkg == null) {
5620                return 0;
5621            }
5622            final BasePermission bp = mSettings.mPermissions.get(name);
5623            if (bp == null) {
5624                return 0;
5625            }
5626            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5627            if (ps == null
5628                    || filterAppAccessLPr(ps, callingUid, userId)) {
5629                return 0;
5630            }
5631            PermissionsState permissionsState = ps.getPermissionsState();
5632            return permissionsState.getPermissionFlags(name, userId);
5633        }
5634    }
5635
5636    @Override
5637    public void updatePermissionFlags(String name, String packageName, int flagMask,
5638            int flagValues, int userId) {
5639        if (!sUserManager.exists(userId)) {
5640            return;
5641        }
5642
5643        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5644
5645        final int callingUid = Binder.getCallingUid();
5646        enforceCrossUserPermission(callingUid, userId,
5647                true /* requireFullPermission */, true /* checkShell */,
5648                "updatePermissionFlags");
5649
5650        // Only the system can change these flags and nothing else.
5651        if (getCallingUid() != Process.SYSTEM_UID) {
5652            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5653            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5654            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5655            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5656            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5657        }
5658
5659        synchronized (mPackages) {
5660            final PackageParser.Package pkg = mPackages.get(packageName);
5661            if (pkg == null) {
5662                throw new IllegalArgumentException("Unknown package: " + packageName);
5663            }
5664            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5665            if (ps == null
5666                    || filterAppAccessLPr(ps, callingUid, userId)) {
5667                throw new IllegalArgumentException("Unknown package: " + packageName);
5668            }
5669
5670            final BasePermission bp = mSettings.mPermissions.get(name);
5671            if (bp == null) {
5672                throw new IllegalArgumentException("Unknown permission: " + name);
5673            }
5674
5675            PermissionsState permissionsState = ps.getPermissionsState();
5676
5677            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5678
5679            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5680                // Install and runtime permissions are stored in different places,
5681                // so figure out what permission changed and persist the change.
5682                if (permissionsState.getInstallPermissionState(name) != null) {
5683                    scheduleWriteSettingsLocked();
5684                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5685                        || hadState) {
5686                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5687                }
5688            }
5689        }
5690    }
5691
5692    /**
5693     * Update the permission flags for all packages and runtime permissions of a user in order
5694     * to allow device or profile owner to remove POLICY_FIXED.
5695     */
5696    @Override
5697    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5698        if (!sUserManager.exists(userId)) {
5699            return;
5700        }
5701
5702        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5703
5704        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5705                true /* requireFullPermission */, true /* checkShell */,
5706                "updatePermissionFlagsForAllApps");
5707
5708        // Only the system can change system fixed flags.
5709        if (getCallingUid() != Process.SYSTEM_UID) {
5710            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5711            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5712        }
5713
5714        synchronized (mPackages) {
5715            boolean changed = false;
5716            final int packageCount = mPackages.size();
5717            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5718                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5719                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5720                if (ps == null) {
5721                    continue;
5722                }
5723                PermissionsState permissionsState = ps.getPermissionsState();
5724                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5725                        userId, flagMask, flagValues);
5726            }
5727            if (changed) {
5728                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5729            }
5730        }
5731    }
5732
5733    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5734        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5735                != PackageManager.PERMISSION_GRANTED
5736            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5737                != PackageManager.PERMISSION_GRANTED) {
5738            throw new SecurityException(message + " requires "
5739                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5740                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5741        }
5742    }
5743
5744    @Override
5745    public boolean shouldShowRequestPermissionRationale(String permissionName,
5746            String packageName, int userId) {
5747        if (UserHandle.getCallingUserId() != userId) {
5748            mContext.enforceCallingPermission(
5749                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5750                    "canShowRequestPermissionRationale for user " + userId);
5751        }
5752
5753        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5754        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5755            return false;
5756        }
5757
5758        if (checkPermission(permissionName, packageName, userId)
5759                == PackageManager.PERMISSION_GRANTED) {
5760            return false;
5761        }
5762
5763        final int flags;
5764
5765        final long identity = Binder.clearCallingIdentity();
5766        try {
5767            flags = getPermissionFlags(permissionName,
5768                    packageName, userId);
5769        } finally {
5770            Binder.restoreCallingIdentity(identity);
5771        }
5772
5773        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5774                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5775                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5776
5777        if ((flags & fixedFlags) != 0) {
5778            return false;
5779        }
5780
5781        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5782    }
5783
5784    @Override
5785    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5786        mContext.enforceCallingOrSelfPermission(
5787                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5788                "addOnPermissionsChangeListener");
5789
5790        synchronized (mPackages) {
5791            mOnPermissionChangeListeners.addListenerLocked(listener);
5792        }
5793    }
5794
5795    @Override
5796    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5797        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5798            throw new SecurityException("Instant applications don't have access to this method");
5799        }
5800        synchronized (mPackages) {
5801            mOnPermissionChangeListeners.removeListenerLocked(listener);
5802        }
5803    }
5804
5805    @Override
5806    public boolean isProtectedBroadcast(String actionName) {
5807        // allow instant applications
5808        synchronized (mPackages) {
5809            if (mProtectedBroadcasts.contains(actionName)) {
5810                return true;
5811            } else if (actionName != null) {
5812                // TODO: remove these terrible hacks
5813                if (actionName.startsWith("android.net.netmon.lingerExpired")
5814                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5815                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5816                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5817                    return true;
5818                }
5819            }
5820        }
5821        return false;
5822    }
5823
5824    @Override
5825    public int checkSignatures(String pkg1, String pkg2) {
5826        synchronized (mPackages) {
5827            final PackageParser.Package p1 = mPackages.get(pkg1);
5828            final PackageParser.Package p2 = mPackages.get(pkg2);
5829            if (p1 == null || p1.mExtras == null
5830                    || p2 == null || p2.mExtras == null) {
5831                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5832            }
5833            final int callingUid = Binder.getCallingUid();
5834            final int callingUserId = UserHandle.getUserId(callingUid);
5835            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5836            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5837            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5838                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5839                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5840            }
5841            return compareSignatures(p1.mSignatures, p2.mSignatures);
5842        }
5843    }
5844
5845    @Override
5846    public int checkUidSignatures(int uid1, int uid2) {
5847        final int callingUid = Binder.getCallingUid();
5848        final int callingUserId = UserHandle.getUserId(callingUid);
5849        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5850        // Map to base uids.
5851        uid1 = UserHandle.getAppId(uid1);
5852        uid2 = UserHandle.getAppId(uid2);
5853        // reader
5854        synchronized (mPackages) {
5855            Signature[] s1;
5856            Signature[] s2;
5857            Object obj = mSettings.getUserIdLPr(uid1);
5858            if (obj != null) {
5859                if (obj instanceof SharedUserSetting) {
5860                    if (isCallerInstantApp) {
5861                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5862                    }
5863                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5864                } else if (obj instanceof PackageSetting) {
5865                    final PackageSetting ps = (PackageSetting) obj;
5866                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5867                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5868                    }
5869                    s1 = ps.signatures.mSignatures;
5870                } else {
5871                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5872                }
5873            } else {
5874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5875            }
5876            obj = mSettings.getUserIdLPr(uid2);
5877            if (obj != null) {
5878                if (obj instanceof SharedUserSetting) {
5879                    if (isCallerInstantApp) {
5880                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5881                    }
5882                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5883                } else if (obj instanceof PackageSetting) {
5884                    final PackageSetting ps = (PackageSetting) obj;
5885                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5886                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5887                    }
5888                    s2 = ps.signatures.mSignatures;
5889                } else {
5890                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5891                }
5892            } else {
5893                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5894            }
5895            return compareSignatures(s1, s2);
5896        }
5897    }
5898
5899    /**
5900     * This method should typically only be used when granting or revoking
5901     * permissions, since the app may immediately restart after this call.
5902     * <p>
5903     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5904     * guard your work against the app being relaunched.
5905     */
5906    private void killUid(int appId, int userId, String reason) {
5907        final long identity = Binder.clearCallingIdentity();
5908        try {
5909            IActivityManager am = ActivityManager.getService();
5910            if (am != null) {
5911                try {
5912                    am.killUid(appId, userId, reason);
5913                } catch (RemoteException e) {
5914                    /* ignore - same process */
5915                }
5916            }
5917        } finally {
5918            Binder.restoreCallingIdentity(identity);
5919        }
5920    }
5921
5922    /**
5923     * Compares two sets of signatures. Returns:
5924     * <br />
5925     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5926     * <br />
5927     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5928     * <br />
5929     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5930     * <br />
5931     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5932     * <br />
5933     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5934     */
5935    static int compareSignatures(Signature[] s1, Signature[] s2) {
5936        if (s1 == null) {
5937            return s2 == null
5938                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5939                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5940        }
5941
5942        if (s2 == null) {
5943            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5944        }
5945
5946        if (s1.length != s2.length) {
5947            return PackageManager.SIGNATURE_NO_MATCH;
5948        }
5949
5950        // Since both signature sets are of size 1, we can compare without HashSets.
5951        if (s1.length == 1) {
5952            return s1[0].equals(s2[0]) ?
5953                    PackageManager.SIGNATURE_MATCH :
5954                    PackageManager.SIGNATURE_NO_MATCH;
5955        }
5956
5957        ArraySet<Signature> set1 = new ArraySet<Signature>();
5958        for (Signature sig : s1) {
5959            set1.add(sig);
5960        }
5961        ArraySet<Signature> set2 = new ArraySet<Signature>();
5962        for (Signature sig : s2) {
5963            set2.add(sig);
5964        }
5965        // Make sure s2 contains all signatures in s1.
5966        if (set1.equals(set2)) {
5967            return PackageManager.SIGNATURE_MATCH;
5968        }
5969        return PackageManager.SIGNATURE_NO_MATCH;
5970    }
5971
5972    /**
5973     * If the database version for this type of package (internal storage or
5974     * external storage) is less than the version where package signatures
5975     * were updated, return true.
5976     */
5977    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5978        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5979        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5980    }
5981
5982    /**
5983     * Used for backward compatibility to make sure any packages with
5984     * certificate chains get upgraded to the new style. {@code existingSigs}
5985     * will be in the old format (since they were stored on disk from before the
5986     * system upgrade) and {@code scannedSigs} will be in the newer format.
5987     */
5988    private int compareSignaturesCompat(PackageSignatures existingSigs,
5989            PackageParser.Package scannedPkg) {
5990        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5991            return PackageManager.SIGNATURE_NO_MATCH;
5992        }
5993
5994        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5995        for (Signature sig : existingSigs.mSignatures) {
5996            existingSet.add(sig);
5997        }
5998        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5999        for (Signature sig : scannedPkg.mSignatures) {
6000            try {
6001                Signature[] chainSignatures = sig.getChainSignatures();
6002                for (Signature chainSig : chainSignatures) {
6003                    scannedCompatSet.add(chainSig);
6004                }
6005            } catch (CertificateEncodingException e) {
6006                scannedCompatSet.add(sig);
6007            }
6008        }
6009        /*
6010         * Make sure the expanded scanned set contains all signatures in the
6011         * existing one.
6012         */
6013        if (scannedCompatSet.equals(existingSet)) {
6014            // Migrate the old signatures to the new scheme.
6015            existingSigs.assignSignatures(scannedPkg.mSignatures);
6016            // The new KeySets will be re-added later in the scanning process.
6017            synchronized (mPackages) {
6018                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6019            }
6020            return PackageManager.SIGNATURE_MATCH;
6021        }
6022        return PackageManager.SIGNATURE_NO_MATCH;
6023    }
6024
6025    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6026        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6027        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6028    }
6029
6030    private int compareSignaturesRecover(PackageSignatures existingSigs,
6031            PackageParser.Package scannedPkg) {
6032        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6033            return PackageManager.SIGNATURE_NO_MATCH;
6034        }
6035
6036        String msg = null;
6037        try {
6038            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6039                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6040                        + scannedPkg.packageName);
6041                return PackageManager.SIGNATURE_MATCH;
6042            }
6043        } catch (CertificateException e) {
6044            msg = e.getMessage();
6045        }
6046
6047        logCriticalInfo(Log.INFO,
6048                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6049        return PackageManager.SIGNATURE_NO_MATCH;
6050    }
6051
6052    @Override
6053    public List<String> getAllPackages() {
6054        final int callingUid = Binder.getCallingUid();
6055        final int callingUserId = UserHandle.getUserId(callingUid);
6056        synchronized (mPackages) {
6057            if (canViewInstantApps(callingUid, callingUserId)) {
6058                return new ArrayList<String>(mPackages.keySet());
6059            }
6060            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6061            final List<String> result = new ArrayList<>();
6062            if (instantAppPkgName != null) {
6063                // caller is an instant application; filter unexposed applications
6064                for (PackageParser.Package pkg : mPackages.values()) {
6065                    if (!pkg.visibleToInstantApps) {
6066                        continue;
6067                    }
6068                    result.add(pkg.packageName);
6069                }
6070            } else {
6071                // caller is a normal application; filter instant applications
6072                for (PackageParser.Package pkg : mPackages.values()) {
6073                    final PackageSetting ps =
6074                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6075                    if (ps != null
6076                            && ps.getInstantApp(callingUserId)
6077                            && !mInstantAppRegistry.isInstantAccessGranted(
6078                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6079                        continue;
6080                    }
6081                    result.add(pkg.packageName);
6082                }
6083            }
6084            return result;
6085        }
6086    }
6087
6088    @Override
6089    public String[] getPackagesForUid(int uid) {
6090        final int callingUid = Binder.getCallingUid();
6091        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6092        final int userId = UserHandle.getUserId(uid);
6093        uid = UserHandle.getAppId(uid);
6094        // reader
6095        synchronized (mPackages) {
6096            Object obj = mSettings.getUserIdLPr(uid);
6097            if (obj instanceof SharedUserSetting) {
6098                if (isCallerInstantApp) {
6099                    return null;
6100                }
6101                final SharedUserSetting sus = (SharedUserSetting) obj;
6102                final int N = sus.packages.size();
6103                String[] res = new String[N];
6104                final Iterator<PackageSetting> it = sus.packages.iterator();
6105                int i = 0;
6106                while (it.hasNext()) {
6107                    PackageSetting ps = it.next();
6108                    if (ps.getInstalled(userId)) {
6109                        res[i++] = ps.name;
6110                    } else {
6111                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6112                    }
6113                }
6114                return res;
6115            } else if (obj instanceof PackageSetting) {
6116                final PackageSetting ps = (PackageSetting) obj;
6117                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6118                    return new String[]{ps.name};
6119                }
6120            }
6121        }
6122        return null;
6123    }
6124
6125    @Override
6126    public String getNameForUid(int uid) {
6127        final int callingUid = Binder.getCallingUid();
6128        if (getInstantAppPackageName(callingUid) != null) {
6129            return null;
6130        }
6131        synchronized (mPackages) {
6132            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6133            if (obj instanceof SharedUserSetting) {
6134                final SharedUserSetting sus = (SharedUserSetting) obj;
6135                return sus.name + ":" + sus.userId;
6136            } else if (obj instanceof PackageSetting) {
6137                final PackageSetting ps = (PackageSetting) obj;
6138                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6139                    return null;
6140                }
6141                return ps.name;
6142            }
6143        }
6144        return null;
6145    }
6146
6147    @Override
6148    public int getUidForSharedUser(String sharedUserName) {
6149        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6150            return -1;
6151        }
6152        if (sharedUserName == null) {
6153            return -1;
6154        }
6155        // reader
6156        synchronized (mPackages) {
6157            SharedUserSetting suid;
6158            try {
6159                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6160                if (suid != null) {
6161                    return suid.userId;
6162                }
6163            } catch (PackageManagerException ignore) {
6164                // can't happen, but, still need to catch it
6165            }
6166            return -1;
6167        }
6168    }
6169
6170    @Override
6171    public int getFlagsForUid(int uid) {
6172        final int callingUid = Binder.getCallingUid();
6173        if (getInstantAppPackageName(callingUid) != null) {
6174            return 0;
6175        }
6176        synchronized (mPackages) {
6177            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6178            if (obj instanceof SharedUserSetting) {
6179                final SharedUserSetting sus = (SharedUserSetting) obj;
6180                return sus.pkgFlags;
6181            } else if (obj instanceof PackageSetting) {
6182                final PackageSetting ps = (PackageSetting) obj;
6183                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6184                    return 0;
6185                }
6186                return ps.pkgFlags;
6187            }
6188        }
6189        return 0;
6190    }
6191
6192    @Override
6193    public int getPrivateFlagsForUid(int uid) {
6194        final int callingUid = Binder.getCallingUid();
6195        if (getInstantAppPackageName(callingUid) != null) {
6196            return 0;
6197        }
6198        synchronized (mPackages) {
6199            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6200            if (obj instanceof SharedUserSetting) {
6201                final SharedUserSetting sus = (SharedUserSetting) obj;
6202                return sus.pkgPrivateFlags;
6203            } else if (obj instanceof PackageSetting) {
6204                final PackageSetting ps = (PackageSetting) obj;
6205                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6206                    return 0;
6207                }
6208                return ps.pkgPrivateFlags;
6209            }
6210        }
6211        return 0;
6212    }
6213
6214    @Override
6215    public boolean isUidPrivileged(int uid) {
6216        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6217            return false;
6218        }
6219        uid = UserHandle.getAppId(uid);
6220        // reader
6221        synchronized (mPackages) {
6222            Object obj = mSettings.getUserIdLPr(uid);
6223            if (obj instanceof SharedUserSetting) {
6224                final SharedUserSetting sus = (SharedUserSetting) obj;
6225                final Iterator<PackageSetting> it = sus.packages.iterator();
6226                while (it.hasNext()) {
6227                    if (it.next().isPrivileged()) {
6228                        return true;
6229                    }
6230                }
6231            } else if (obj instanceof PackageSetting) {
6232                final PackageSetting ps = (PackageSetting) obj;
6233                return ps.isPrivileged();
6234            }
6235        }
6236        return false;
6237    }
6238
6239    @Override
6240    public String[] getAppOpPermissionPackages(String permissionName) {
6241        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6242            return null;
6243        }
6244        synchronized (mPackages) {
6245            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6246            if (pkgs == null) {
6247                return null;
6248            }
6249            return pkgs.toArray(new String[pkgs.size()]);
6250        }
6251    }
6252
6253    @Override
6254    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6255            int flags, int userId) {
6256        return resolveIntentInternal(
6257                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6258    }
6259
6260    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6261            int flags, int userId, boolean resolveForStart) {
6262        try {
6263            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6264
6265            if (!sUserManager.exists(userId)) return null;
6266            final int callingUid = Binder.getCallingUid();
6267            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6268            enforceCrossUserPermission(callingUid, userId,
6269                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6270
6271            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6272            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6273                    flags, callingUid, userId, resolveForStart);
6274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6275
6276            final ResolveInfo bestChoice =
6277                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6278            return bestChoice;
6279        } finally {
6280            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6281        }
6282    }
6283
6284    @Override
6285    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6286        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6287            throw new SecurityException(
6288                    "findPersistentPreferredActivity can only be run by the system");
6289        }
6290        if (!sUserManager.exists(userId)) {
6291            return null;
6292        }
6293        final int callingUid = Binder.getCallingUid();
6294        intent = updateIntentForResolve(intent);
6295        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6296        final int flags = updateFlagsForResolve(
6297                0, userId, intent, callingUid, false /*includeInstantApps*/);
6298        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6299                userId);
6300        synchronized (mPackages) {
6301            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6302                    userId);
6303        }
6304    }
6305
6306    @Override
6307    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6308            IntentFilter filter, int match, ComponentName activity) {
6309        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6310            return;
6311        }
6312        final int userId = UserHandle.getCallingUserId();
6313        if (DEBUG_PREFERRED) {
6314            Log.v(TAG, "setLastChosenActivity intent=" + intent
6315                + " resolvedType=" + resolvedType
6316                + " flags=" + flags
6317                + " filter=" + filter
6318                + " match=" + match
6319                + " activity=" + activity);
6320            filter.dump(new PrintStreamPrinter(System.out), "    ");
6321        }
6322        intent.setComponent(null);
6323        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6324                userId);
6325        // Find any earlier preferred or last chosen entries and nuke them
6326        findPreferredActivity(intent, resolvedType,
6327                flags, query, 0, false, true, false, userId);
6328        // Add the new activity as the last chosen for this filter
6329        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6330                "Setting last chosen");
6331    }
6332
6333    @Override
6334    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6335        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6336            return null;
6337        }
6338        final int userId = UserHandle.getCallingUserId();
6339        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6340        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6341                userId);
6342        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6343                false, false, false, userId);
6344    }
6345
6346    /**
6347     * Returns whether or not instant apps have been disabled remotely.
6348     */
6349    private boolean isEphemeralDisabled() {
6350        return mEphemeralAppsDisabled;
6351    }
6352
6353    private boolean isInstantAppAllowed(
6354            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6355            boolean skipPackageCheck) {
6356        if (mInstantAppResolverConnection == null) {
6357            return false;
6358        }
6359        if (mInstantAppInstallerActivity == null) {
6360            return false;
6361        }
6362        if (intent.getComponent() != null) {
6363            return false;
6364        }
6365        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6366            return false;
6367        }
6368        if (!skipPackageCheck && intent.getPackage() != null) {
6369            return false;
6370        }
6371        final boolean isWebUri = hasWebURI(intent);
6372        if (!isWebUri || intent.getData().getHost() == null) {
6373            return false;
6374        }
6375        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6376        // Or if there's already an ephemeral app installed that handles the action
6377        synchronized (mPackages) {
6378            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6379            for (int n = 0; n < count; n++) {
6380                final ResolveInfo info = resolvedActivities.get(n);
6381                final String packageName = info.activityInfo.packageName;
6382                final PackageSetting ps = mSettings.mPackages.get(packageName);
6383                if (ps != null) {
6384                    // only check domain verification status if the app is not a browser
6385                    if (!info.handleAllWebDataURI) {
6386                        // Try to get the status from User settings first
6387                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6388                        final int status = (int) (packedStatus >> 32);
6389                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6390                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6391                            if (DEBUG_EPHEMERAL) {
6392                                Slog.v(TAG, "DENY instant app;"
6393                                    + " pkg: " + packageName + ", status: " + status);
6394                            }
6395                            return false;
6396                        }
6397                    }
6398                    if (ps.getInstantApp(userId)) {
6399                        if (DEBUG_EPHEMERAL) {
6400                            Slog.v(TAG, "DENY instant app installed;"
6401                                    + " pkg: " + packageName);
6402                        }
6403                        return false;
6404                    }
6405                }
6406            }
6407        }
6408        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6409        return true;
6410    }
6411
6412    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6413            Intent origIntent, String resolvedType, String callingPackage,
6414            Bundle verificationBundle, int userId) {
6415        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6416                new InstantAppRequest(responseObj, origIntent, resolvedType,
6417                        callingPackage, userId, verificationBundle));
6418        mHandler.sendMessage(msg);
6419    }
6420
6421    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6422            int flags, List<ResolveInfo> query, int userId) {
6423        if (query != null) {
6424            final int N = query.size();
6425            if (N == 1) {
6426                return query.get(0);
6427            } else if (N > 1) {
6428                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6429                // If there is more than one activity with the same priority,
6430                // then let the user decide between them.
6431                ResolveInfo r0 = query.get(0);
6432                ResolveInfo r1 = query.get(1);
6433                if (DEBUG_INTENT_MATCHING || debug) {
6434                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6435                            + r1.activityInfo.name + "=" + r1.priority);
6436                }
6437                // If the first activity has a higher priority, or a different
6438                // default, then it is always desirable to pick it.
6439                if (r0.priority != r1.priority
6440                        || r0.preferredOrder != r1.preferredOrder
6441                        || r0.isDefault != r1.isDefault) {
6442                    return query.get(0);
6443                }
6444                // If we have saved a preference for a preferred activity for
6445                // this Intent, use that.
6446                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6447                        flags, query, r0.priority, true, false, debug, userId);
6448                if (ri != null) {
6449                    return ri;
6450                }
6451                // If we have an ephemeral app, use it
6452                for (int i = 0; i < N; i++) {
6453                    ri = query.get(i);
6454                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6455                        final String packageName = ri.activityInfo.packageName;
6456                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6457                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6458                        final int status = (int)(packedStatus >> 32);
6459                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6460                            return ri;
6461                        }
6462                    }
6463                }
6464                ri = new ResolveInfo(mResolveInfo);
6465                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6466                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6467                // If all of the options come from the same package, show the application's
6468                // label and icon instead of the generic resolver's.
6469                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6470                // and then throw away the ResolveInfo itself, meaning that the caller loses
6471                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6472                // a fallback for this case; we only set the target package's resources on
6473                // the ResolveInfo, not the ActivityInfo.
6474                final String intentPackage = intent.getPackage();
6475                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6476                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6477                    ri.resolvePackageName = intentPackage;
6478                    if (userNeedsBadging(userId)) {
6479                        ri.noResourceId = true;
6480                    } else {
6481                        ri.icon = appi.icon;
6482                    }
6483                    ri.iconResourceId = appi.icon;
6484                    ri.labelRes = appi.labelRes;
6485                }
6486                ri.activityInfo.applicationInfo = new ApplicationInfo(
6487                        ri.activityInfo.applicationInfo);
6488                if (userId != 0) {
6489                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6490                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6491                }
6492                // Make sure that the resolver is displayable in car mode
6493                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6494                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6495                return ri;
6496            }
6497        }
6498        return null;
6499    }
6500
6501    /**
6502     * Return true if the given list is not empty and all of its contents have
6503     * an activityInfo with the given package name.
6504     */
6505    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6506        if (ArrayUtils.isEmpty(list)) {
6507            return false;
6508        }
6509        for (int i = 0, N = list.size(); i < N; i++) {
6510            final ResolveInfo ri = list.get(i);
6511            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6512            if (ai == null || !packageName.equals(ai.packageName)) {
6513                return false;
6514            }
6515        }
6516        return true;
6517    }
6518
6519    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6520            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6521        final int N = query.size();
6522        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6523                .get(userId);
6524        // Get the list of persistent preferred activities that handle the intent
6525        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6526        List<PersistentPreferredActivity> pprefs = ppir != null
6527                ? ppir.queryIntent(intent, resolvedType,
6528                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6529                        userId)
6530                : null;
6531        if (pprefs != null && pprefs.size() > 0) {
6532            final int M = pprefs.size();
6533            for (int i=0; i<M; i++) {
6534                final PersistentPreferredActivity ppa = pprefs.get(i);
6535                if (DEBUG_PREFERRED || debug) {
6536                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6537                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6538                            + "\n  component=" + ppa.mComponent);
6539                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6540                }
6541                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6542                        flags | MATCH_DISABLED_COMPONENTS, userId);
6543                if (DEBUG_PREFERRED || debug) {
6544                    Slog.v(TAG, "Found persistent preferred activity:");
6545                    if (ai != null) {
6546                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6547                    } else {
6548                        Slog.v(TAG, "  null");
6549                    }
6550                }
6551                if (ai == null) {
6552                    // This previously registered persistent preferred activity
6553                    // component is no longer known. Ignore it and do NOT remove it.
6554                    continue;
6555                }
6556                for (int j=0; j<N; j++) {
6557                    final ResolveInfo ri = query.get(j);
6558                    if (!ri.activityInfo.applicationInfo.packageName
6559                            .equals(ai.applicationInfo.packageName)) {
6560                        continue;
6561                    }
6562                    if (!ri.activityInfo.name.equals(ai.name)) {
6563                        continue;
6564                    }
6565                    //  Found a persistent preference that can handle the intent.
6566                    if (DEBUG_PREFERRED || debug) {
6567                        Slog.v(TAG, "Returning persistent preferred activity: " +
6568                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6569                    }
6570                    return ri;
6571                }
6572            }
6573        }
6574        return null;
6575    }
6576
6577    // TODO: handle preferred activities missing while user has amnesia
6578    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6579            List<ResolveInfo> query, int priority, boolean always,
6580            boolean removeMatches, boolean debug, int userId) {
6581        if (!sUserManager.exists(userId)) return null;
6582        final int callingUid = Binder.getCallingUid();
6583        flags = updateFlagsForResolve(
6584                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6585        intent = updateIntentForResolve(intent);
6586        // writer
6587        synchronized (mPackages) {
6588            // Try to find a matching persistent preferred activity.
6589            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6590                    debug, userId);
6591
6592            // If a persistent preferred activity matched, use it.
6593            if (pri != null) {
6594                return pri;
6595            }
6596
6597            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6598            // Get the list of preferred activities that handle the intent
6599            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6600            List<PreferredActivity> prefs = pir != null
6601                    ? pir.queryIntent(intent, resolvedType,
6602                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6603                            userId)
6604                    : null;
6605            if (prefs != null && prefs.size() > 0) {
6606                boolean changed = false;
6607                try {
6608                    // First figure out how good the original match set is.
6609                    // We will only allow preferred activities that came
6610                    // from the same match quality.
6611                    int match = 0;
6612
6613                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6614
6615                    final int N = query.size();
6616                    for (int j=0; j<N; j++) {
6617                        final ResolveInfo ri = query.get(j);
6618                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6619                                + ": 0x" + Integer.toHexString(match));
6620                        if (ri.match > match) {
6621                            match = ri.match;
6622                        }
6623                    }
6624
6625                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6626                            + Integer.toHexString(match));
6627
6628                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6629                    final int M = prefs.size();
6630                    for (int i=0; i<M; i++) {
6631                        final PreferredActivity pa = prefs.get(i);
6632                        if (DEBUG_PREFERRED || debug) {
6633                            Slog.v(TAG, "Checking PreferredActivity ds="
6634                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6635                                    + "\n  component=" + pa.mPref.mComponent);
6636                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6637                        }
6638                        if (pa.mPref.mMatch != match) {
6639                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6640                                    + Integer.toHexString(pa.mPref.mMatch));
6641                            continue;
6642                        }
6643                        // If it's not an "always" type preferred activity and that's what we're
6644                        // looking for, skip it.
6645                        if (always && !pa.mPref.mAlways) {
6646                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6647                            continue;
6648                        }
6649                        final ActivityInfo ai = getActivityInfo(
6650                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6651                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6652                                userId);
6653                        if (DEBUG_PREFERRED || debug) {
6654                            Slog.v(TAG, "Found preferred activity:");
6655                            if (ai != null) {
6656                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6657                            } else {
6658                                Slog.v(TAG, "  null");
6659                            }
6660                        }
6661                        if (ai == null) {
6662                            // This previously registered preferred activity
6663                            // component is no longer known.  Most likely an update
6664                            // to the app was installed and in the new version this
6665                            // component no longer exists.  Clean it up by removing
6666                            // it from the preferred activities list, and skip it.
6667                            Slog.w(TAG, "Removing dangling preferred activity: "
6668                                    + pa.mPref.mComponent);
6669                            pir.removeFilter(pa);
6670                            changed = true;
6671                            continue;
6672                        }
6673                        for (int j=0; j<N; j++) {
6674                            final ResolveInfo ri = query.get(j);
6675                            if (!ri.activityInfo.applicationInfo.packageName
6676                                    .equals(ai.applicationInfo.packageName)) {
6677                                continue;
6678                            }
6679                            if (!ri.activityInfo.name.equals(ai.name)) {
6680                                continue;
6681                            }
6682
6683                            if (removeMatches) {
6684                                pir.removeFilter(pa);
6685                                changed = true;
6686                                if (DEBUG_PREFERRED) {
6687                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6688                                }
6689                                break;
6690                            }
6691
6692                            // Okay we found a previously set preferred or last chosen app.
6693                            // If the result set is different from when this
6694                            // was created, we need to clear it and re-ask the
6695                            // user their preference, if we're looking for an "always" type entry.
6696                            if (always && !pa.mPref.sameSet(query)) {
6697                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6698                                        + intent + " type " + resolvedType);
6699                                if (DEBUG_PREFERRED) {
6700                                    Slog.v(TAG, "Removing preferred activity since set changed "
6701                                            + pa.mPref.mComponent);
6702                                }
6703                                pir.removeFilter(pa);
6704                                // Re-add the filter as a "last chosen" entry (!always)
6705                                PreferredActivity lastChosen = new PreferredActivity(
6706                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6707                                pir.addFilter(lastChosen);
6708                                changed = true;
6709                                return null;
6710                            }
6711
6712                            // Yay! Either the set matched or we're looking for the last chosen
6713                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6714                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6715                            return ri;
6716                        }
6717                    }
6718                } finally {
6719                    if (changed) {
6720                        if (DEBUG_PREFERRED) {
6721                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6722                        }
6723                        scheduleWritePackageRestrictionsLocked(userId);
6724                    }
6725                }
6726            }
6727        }
6728        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6729        return null;
6730    }
6731
6732    /*
6733     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6734     */
6735    @Override
6736    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6737            int targetUserId) {
6738        mContext.enforceCallingOrSelfPermission(
6739                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6740        List<CrossProfileIntentFilter> matches =
6741                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6742        if (matches != null) {
6743            int size = matches.size();
6744            for (int i = 0; i < size; i++) {
6745                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6746            }
6747        }
6748        if (hasWebURI(intent)) {
6749            // cross-profile app linking works only towards the parent.
6750            final int callingUid = Binder.getCallingUid();
6751            final UserInfo parent = getProfileParent(sourceUserId);
6752            synchronized(mPackages) {
6753                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6754                        false /*includeInstantApps*/);
6755                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6756                        intent, resolvedType, flags, sourceUserId, parent.id);
6757                return xpDomainInfo != null;
6758            }
6759        }
6760        return false;
6761    }
6762
6763    private UserInfo getProfileParent(int userId) {
6764        final long identity = Binder.clearCallingIdentity();
6765        try {
6766            return sUserManager.getProfileParent(userId);
6767        } finally {
6768            Binder.restoreCallingIdentity(identity);
6769        }
6770    }
6771
6772    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6773            String resolvedType, int userId) {
6774        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6775        if (resolver != null) {
6776            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6777        }
6778        return null;
6779    }
6780
6781    @Override
6782    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6783            String resolvedType, int flags, int userId) {
6784        try {
6785            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6786
6787            return new ParceledListSlice<>(
6788                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6789        } finally {
6790            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6791        }
6792    }
6793
6794    /**
6795     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6796     * instant, returns {@code null}.
6797     */
6798    private String getInstantAppPackageName(int callingUid) {
6799        synchronized (mPackages) {
6800            // If the caller is an isolated app use the owner's uid for the lookup.
6801            if (Process.isIsolated(callingUid)) {
6802                callingUid = mIsolatedOwners.get(callingUid);
6803            }
6804            final int appId = UserHandle.getAppId(callingUid);
6805            final Object obj = mSettings.getUserIdLPr(appId);
6806            if (obj instanceof PackageSetting) {
6807                final PackageSetting ps = (PackageSetting) obj;
6808                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6809                return isInstantApp ? ps.pkg.packageName : null;
6810            }
6811        }
6812        return null;
6813    }
6814
6815    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6816            String resolvedType, int flags, int userId) {
6817        return queryIntentActivitiesInternal(
6818                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6819    }
6820
6821    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6822            String resolvedType, int flags, int filterCallingUid, int userId,
6823            boolean resolveForStart) {
6824        if (!sUserManager.exists(userId)) return Collections.emptyList();
6825        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6826        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6827                false /* requireFullPermission */, false /* checkShell */,
6828                "query intent activities");
6829        final String pkgName = intent.getPackage();
6830        ComponentName comp = intent.getComponent();
6831        if (comp == null) {
6832            if (intent.getSelector() != null) {
6833                intent = intent.getSelector();
6834                comp = intent.getComponent();
6835            }
6836        }
6837
6838        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6839                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6840        if (comp != null) {
6841            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6842            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6843            if (ai != null) {
6844                // When specifying an explicit component, we prevent the activity from being
6845                // used when either 1) the calling package is normal and the activity is within
6846                // an ephemeral application or 2) the calling package is ephemeral and the
6847                // activity is not visible to ephemeral applications.
6848                final boolean matchInstantApp =
6849                        (flags & PackageManager.MATCH_INSTANT) != 0;
6850                final boolean matchVisibleToInstantAppOnly =
6851                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6852                final boolean matchExplicitlyVisibleOnly =
6853                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6854                final boolean isCallerInstantApp =
6855                        instantAppPkgName != null;
6856                final boolean isTargetSameInstantApp =
6857                        comp.getPackageName().equals(instantAppPkgName);
6858                final boolean isTargetInstantApp =
6859                        (ai.applicationInfo.privateFlags
6860                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6861                final boolean isTargetVisibleToInstantApp =
6862                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6863                final boolean isTargetExplicitlyVisibleToInstantApp =
6864                        isTargetVisibleToInstantApp
6865                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6866                final boolean isTargetHiddenFromInstantApp =
6867                        !isTargetVisibleToInstantApp
6868                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6869                final boolean blockResolution =
6870                        !isTargetSameInstantApp
6871                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6872                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6873                                        && isTargetHiddenFromInstantApp));
6874                if (!blockResolution) {
6875                    final ResolveInfo ri = new ResolveInfo();
6876                    ri.activityInfo = ai;
6877                    list.add(ri);
6878                }
6879            }
6880            return applyPostResolutionFilter(list, instantAppPkgName);
6881        }
6882
6883        // reader
6884        boolean sortResult = false;
6885        boolean addEphemeral = false;
6886        List<ResolveInfo> result;
6887        final boolean ephemeralDisabled = isEphemeralDisabled();
6888        synchronized (mPackages) {
6889            if (pkgName == null) {
6890                List<CrossProfileIntentFilter> matchingFilters =
6891                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6892                // Check for results that need to skip the current profile.
6893                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6894                        resolvedType, flags, userId);
6895                if (xpResolveInfo != null) {
6896                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6897                    xpResult.add(xpResolveInfo);
6898                    return applyPostResolutionFilter(
6899                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6900                }
6901
6902                // Check for results in the current profile.
6903                result = filterIfNotSystemUser(mActivities.queryIntent(
6904                        intent, resolvedType, flags, userId), userId);
6905                addEphemeral = !ephemeralDisabled
6906                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6907                // Check for cross profile results.
6908                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6909                xpResolveInfo = queryCrossProfileIntents(
6910                        matchingFilters, intent, resolvedType, flags, userId,
6911                        hasNonNegativePriorityResult);
6912                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6913                    boolean isVisibleToUser = filterIfNotSystemUser(
6914                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6915                    if (isVisibleToUser) {
6916                        result.add(xpResolveInfo);
6917                        sortResult = true;
6918                    }
6919                }
6920                if (hasWebURI(intent)) {
6921                    CrossProfileDomainInfo xpDomainInfo = null;
6922                    final UserInfo parent = getProfileParent(userId);
6923                    if (parent != null) {
6924                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6925                                flags, userId, parent.id);
6926                    }
6927                    if (xpDomainInfo != null) {
6928                        if (xpResolveInfo != null) {
6929                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6930                            // in the result.
6931                            result.remove(xpResolveInfo);
6932                        }
6933                        if (result.size() == 0 && !addEphemeral) {
6934                            // No result in current profile, but found candidate in parent user.
6935                            // And we are not going to add emphemeral app, so we can return the
6936                            // result straight away.
6937                            result.add(xpDomainInfo.resolveInfo);
6938                            return applyPostResolutionFilter(result, instantAppPkgName);
6939                        }
6940                    } else if (result.size() <= 1 && !addEphemeral) {
6941                        // No result in parent user and <= 1 result in current profile, and we
6942                        // are not going to add emphemeral app, so we can return the result without
6943                        // further processing.
6944                        return applyPostResolutionFilter(result, instantAppPkgName);
6945                    }
6946                    // We have more than one candidate (combining results from current and parent
6947                    // profile), so we need filtering and sorting.
6948                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6949                            intent, flags, result, xpDomainInfo, userId);
6950                    sortResult = true;
6951                }
6952            } else {
6953                final PackageParser.Package pkg = mPackages.get(pkgName);
6954                result = null;
6955                if (pkg != null) {
6956                    result = filterIfNotSystemUser(
6957                            mActivities.queryIntentForPackage(
6958                                    intent, resolvedType, flags, pkg.activities, userId),
6959                            userId);
6960                }
6961                if (result == null || result.size() == 0) {
6962                    // the caller wants to resolve for a particular package; however, there
6963                    // were no installed results, so, try to find an ephemeral result
6964                    addEphemeral = !ephemeralDisabled
6965                            && isInstantAppAllowed(
6966                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6967                    if (result == null) {
6968                        result = new ArrayList<>();
6969                    }
6970                }
6971            }
6972        }
6973        if (addEphemeral) {
6974            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6975        }
6976        if (sortResult) {
6977            Collections.sort(result, mResolvePrioritySorter);
6978        }
6979        return applyPostResolutionFilter(result, instantAppPkgName);
6980    }
6981
6982    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6983            String resolvedType, int flags, int userId) {
6984        // first, check to see if we've got an instant app already installed
6985        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6986        ResolveInfo localInstantApp = null;
6987        boolean blockResolution = false;
6988        if (!alreadyResolvedLocally) {
6989            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6990                    flags
6991                        | PackageManager.GET_RESOLVED_FILTER
6992                        | PackageManager.MATCH_INSTANT
6993                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6994                    userId);
6995            for (int i = instantApps.size() - 1; i >= 0; --i) {
6996                final ResolveInfo info = instantApps.get(i);
6997                final String packageName = info.activityInfo.packageName;
6998                final PackageSetting ps = mSettings.mPackages.get(packageName);
6999                if (ps.getInstantApp(userId)) {
7000                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7001                    final int status = (int)(packedStatus >> 32);
7002                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7003                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7004                        // there's a local instant application installed, but, the user has
7005                        // chosen to never use it; skip resolution and don't acknowledge
7006                        // an instant application is even available
7007                        if (DEBUG_EPHEMERAL) {
7008                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7009                        }
7010                        blockResolution = true;
7011                        break;
7012                    } else {
7013                        // we have a locally installed instant application; skip resolution
7014                        // but acknowledge there's an instant application available
7015                        if (DEBUG_EPHEMERAL) {
7016                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7017                        }
7018                        localInstantApp = info;
7019                        break;
7020                    }
7021                }
7022            }
7023        }
7024        // no app installed, let's see if one's available
7025        AuxiliaryResolveInfo auxiliaryResponse = null;
7026        if (!blockResolution) {
7027            if (localInstantApp == null) {
7028                // we don't have an instant app locally, resolve externally
7029                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7030                final InstantAppRequest requestObject = new InstantAppRequest(
7031                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7032                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7033                auxiliaryResponse =
7034                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7035                                mContext, mInstantAppResolverConnection, requestObject);
7036                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7037            } else {
7038                // we have an instant application locally, but, we can't admit that since
7039                // callers shouldn't be able to determine prior browsing. create a dummy
7040                // auxiliary response so the downstream code behaves as if there's an
7041                // instant application available externally. when it comes time to start
7042                // the instant application, we'll do the right thing.
7043                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7044                auxiliaryResponse = new AuxiliaryResolveInfo(
7045                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7046            }
7047        }
7048        if (auxiliaryResponse != null) {
7049            if (DEBUG_EPHEMERAL) {
7050                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7051            }
7052            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7053            final PackageSetting ps =
7054                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7055            if (ps != null) {
7056                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7057                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7058                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7059                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7060                // make sure this resolver is the default
7061                ephemeralInstaller.isDefault = true;
7062                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7063                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7064                // add a non-generic filter
7065                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7066                ephemeralInstaller.filter.addDataPath(
7067                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7068                ephemeralInstaller.isInstantAppAvailable = true;
7069                result.add(ephemeralInstaller);
7070            }
7071        }
7072        return result;
7073    }
7074
7075    private static class CrossProfileDomainInfo {
7076        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7077        ResolveInfo resolveInfo;
7078        /* Best domain verification status of the activities found in the other profile */
7079        int bestDomainVerificationStatus;
7080    }
7081
7082    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7083            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7084        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7085                sourceUserId)) {
7086            return null;
7087        }
7088        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7089                resolvedType, flags, parentUserId);
7090
7091        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7092            return null;
7093        }
7094        CrossProfileDomainInfo result = null;
7095        int size = resultTargetUser.size();
7096        for (int i = 0; i < size; i++) {
7097            ResolveInfo riTargetUser = resultTargetUser.get(i);
7098            // Intent filter verification is only for filters that specify a host. So don't return
7099            // those that handle all web uris.
7100            if (riTargetUser.handleAllWebDataURI) {
7101                continue;
7102            }
7103            String packageName = riTargetUser.activityInfo.packageName;
7104            PackageSetting ps = mSettings.mPackages.get(packageName);
7105            if (ps == null) {
7106                continue;
7107            }
7108            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7109            int status = (int)(verificationState >> 32);
7110            if (result == null) {
7111                result = new CrossProfileDomainInfo();
7112                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7113                        sourceUserId, parentUserId);
7114                result.bestDomainVerificationStatus = status;
7115            } else {
7116                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7117                        result.bestDomainVerificationStatus);
7118            }
7119        }
7120        // Don't consider matches with status NEVER across profiles.
7121        if (result != null && result.bestDomainVerificationStatus
7122                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7123            return null;
7124        }
7125        return result;
7126    }
7127
7128    /**
7129     * Verification statuses are ordered from the worse to the best, except for
7130     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7131     */
7132    private int bestDomainVerificationStatus(int status1, int status2) {
7133        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7134            return status2;
7135        }
7136        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7137            return status1;
7138        }
7139        return (int) MathUtils.max(status1, status2);
7140    }
7141
7142    private boolean isUserEnabled(int userId) {
7143        long callingId = Binder.clearCallingIdentity();
7144        try {
7145            UserInfo userInfo = sUserManager.getUserInfo(userId);
7146            return userInfo != null && userInfo.isEnabled();
7147        } finally {
7148            Binder.restoreCallingIdentity(callingId);
7149        }
7150    }
7151
7152    /**
7153     * Filter out activities with systemUserOnly flag set, when current user is not System.
7154     *
7155     * @return filtered list
7156     */
7157    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7158        if (userId == UserHandle.USER_SYSTEM) {
7159            return resolveInfos;
7160        }
7161        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7162            ResolveInfo info = resolveInfos.get(i);
7163            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7164                resolveInfos.remove(i);
7165            }
7166        }
7167        return resolveInfos;
7168    }
7169
7170    /**
7171     * Filters out ephemeral activities.
7172     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7173     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7174     *
7175     * @param resolveInfos The pre-filtered list of resolved activities
7176     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7177     *          is performed.
7178     * @return A filtered list of resolved activities.
7179     */
7180    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7181            String ephemeralPkgName) {
7182        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7183            final ResolveInfo info = resolveInfos.get(i);
7184            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7185            // TODO: When adding on-demand split support for non-instant apps, remove this check
7186            // and always apply post filtering
7187            // allow activities that are defined in the provided package
7188            if (isEphemeralApp) {
7189                if (info.activityInfo.splitName != null
7190                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7191                                info.activityInfo.splitName)) {
7192                    // requested activity is defined in a split that hasn't been installed yet.
7193                    // add the installer to the resolve list
7194                    if (DEBUG_EPHEMERAL) {
7195                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7196                    }
7197                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7198                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7199                            info.activityInfo.packageName, info.activityInfo.splitName,
7200                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7201                    // make sure this resolver is the default
7202                    installerInfo.isDefault = true;
7203                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7204                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7205                    // add a non-generic filter
7206                    installerInfo.filter = new IntentFilter();
7207                    // load resources from the correct package
7208                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7209                    resolveInfos.set(i, installerInfo);
7210                    continue;
7211                }
7212            }
7213            // caller is a full app, don't need to apply any other filtering
7214            if (ephemeralPkgName == null) {
7215                continue;
7216            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7217                // caller is same app; don't need to apply any other filtering
7218                continue;
7219            }
7220            // allow activities that have been explicitly exposed to ephemeral apps
7221            if (!isEphemeralApp
7222                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7223                continue;
7224            }
7225            resolveInfos.remove(i);
7226        }
7227        return resolveInfos;
7228    }
7229
7230    /**
7231     * @param resolveInfos list of resolve infos in descending priority order
7232     * @return if the list contains a resolve info with non-negative priority
7233     */
7234    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7235        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7236    }
7237
7238    private static boolean hasWebURI(Intent intent) {
7239        if (intent.getData() == null) {
7240            return false;
7241        }
7242        final String scheme = intent.getScheme();
7243        if (TextUtils.isEmpty(scheme)) {
7244            return false;
7245        }
7246        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7247    }
7248
7249    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7250            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7251            int userId) {
7252        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7253
7254        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7255            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7256                    candidates.size());
7257        }
7258
7259        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7260        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7261        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7264        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7265
7266        synchronized (mPackages) {
7267            final int count = candidates.size();
7268            // First, try to use linked apps. Partition the candidates into four lists:
7269            // one for the final results, one for the "do not use ever", one for "undefined status"
7270            // and finally one for "browser app type".
7271            for (int n=0; n<count; n++) {
7272                ResolveInfo info = candidates.get(n);
7273                String packageName = info.activityInfo.packageName;
7274                PackageSetting ps = mSettings.mPackages.get(packageName);
7275                if (ps != null) {
7276                    // Add to the special match all list (Browser use case)
7277                    if (info.handleAllWebDataURI) {
7278                        matchAllList.add(info);
7279                        continue;
7280                    }
7281                    // Try to get the status from User settings first
7282                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7283                    int status = (int)(packedStatus >> 32);
7284                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7285                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7286                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7287                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7288                                    + " : linkgen=" + linkGeneration);
7289                        }
7290                        // Use link-enabled generation as preferredOrder, i.e.
7291                        // prefer newly-enabled over earlier-enabled.
7292                        info.preferredOrder = linkGeneration;
7293                        alwaysList.add(info);
7294                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7295                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7296                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7297                        }
7298                        neverList.add(info);
7299                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7300                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7301                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7302                        }
7303                        alwaysAskList.add(info);
7304                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7305                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7306                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7307                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7308                        }
7309                        undefinedList.add(info);
7310                    }
7311                }
7312            }
7313
7314            // We'll want to include browser possibilities in a few cases
7315            boolean includeBrowser = false;
7316
7317            // First try to add the "always" resolution(s) for the current user, if any
7318            if (alwaysList.size() > 0) {
7319                result.addAll(alwaysList);
7320            } else {
7321                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7322                result.addAll(undefinedList);
7323                // Maybe add one for the other profile.
7324                if (xpDomainInfo != null && (
7325                        xpDomainInfo.bestDomainVerificationStatus
7326                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7327                    result.add(xpDomainInfo.resolveInfo);
7328                }
7329                includeBrowser = true;
7330            }
7331
7332            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7333            // If there were 'always' entries their preferred order has been set, so we also
7334            // back that off to make the alternatives equivalent
7335            if (alwaysAskList.size() > 0) {
7336                for (ResolveInfo i : result) {
7337                    i.preferredOrder = 0;
7338                }
7339                result.addAll(alwaysAskList);
7340                includeBrowser = true;
7341            }
7342
7343            if (includeBrowser) {
7344                // Also add browsers (all of them or only the default one)
7345                if (DEBUG_DOMAIN_VERIFICATION) {
7346                    Slog.v(TAG, "   ...including browsers in candidate set");
7347                }
7348                if ((matchFlags & MATCH_ALL) != 0) {
7349                    result.addAll(matchAllList);
7350                } else {
7351                    // Browser/generic handling case.  If there's a default browser, go straight
7352                    // to that (but only if there is no other higher-priority match).
7353                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7354                    int maxMatchPrio = 0;
7355                    ResolveInfo defaultBrowserMatch = null;
7356                    final int numCandidates = matchAllList.size();
7357                    for (int n = 0; n < numCandidates; n++) {
7358                        ResolveInfo info = matchAllList.get(n);
7359                        // track the highest overall match priority...
7360                        if (info.priority > maxMatchPrio) {
7361                            maxMatchPrio = info.priority;
7362                        }
7363                        // ...and the highest-priority default browser match
7364                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7365                            if (defaultBrowserMatch == null
7366                                    || (defaultBrowserMatch.priority < info.priority)) {
7367                                if (debug) {
7368                                    Slog.v(TAG, "Considering default browser match " + info);
7369                                }
7370                                defaultBrowserMatch = info;
7371                            }
7372                        }
7373                    }
7374                    if (defaultBrowserMatch != null
7375                            && defaultBrowserMatch.priority >= maxMatchPrio
7376                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7377                    {
7378                        if (debug) {
7379                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7380                        }
7381                        result.add(defaultBrowserMatch);
7382                    } else {
7383                        result.addAll(matchAllList);
7384                    }
7385                }
7386
7387                // If there is nothing selected, add all candidates and remove the ones that the user
7388                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7389                if (result.size() == 0) {
7390                    result.addAll(candidates);
7391                    result.removeAll(neverList);
7392                }
7393            }
7394        }
7395        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7396            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7397                    result.size());
7398            for (ResolveInfo info : result) {
7399                Slog.v(TAG, "  + " + info.activityInfo);
7400            }
7401        }
7402        return result;
7403    }
7404
7405    // Returns a packed value as a long:
7406    //
7407    // high 'int'-sized word: link status: undefined/ask/never/always.
7408    // low 'int'-sized word: relative priority among 'always' results.
7409    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7410        long result = ps.getDomainVerificationStatusForUser(userId);
7411        // if none available, get the master status
7412        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7413            if (ps.getIntentFilterVerificationInfo() != null) {
7414                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7415            }
7416        }
7417        return result;
7418    }
7419
7420    private ResolveInfo querySkipCurrentProfileIntents(
7421            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7422            int flags, int sourceUserId) {
7423        if (matchingFilters != null) {
7424            int size = matchingFilters.size();
7425            for (int i = 0; i < size; i ++) {
7426                CrossProfileIntentFilter filter = matchingFilters.get(i);
7427                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7428                    // Checking if there are activities in the target user that can handle the
7429                    // intent.
7430                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7431                            resolvedType, flags, sourceUserId);
7432                    if (resolveInfo != null) {
7433                        return resolveInfo;
7434                    }
7435                }
7436            }
7437        }
7438        return null;
7439    }
7440
7441    // Return matching ResolveInfo in target user if any.
7442    private ResolveInfo queryCrossProfileIntents(
7443            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7444            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7445        if (matchingFilters != null) {
7446            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7447            // match the same intent. For performance reasons, it is better not to
7448            // run queryIntent twice for the same userId
7449            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7450            int size = matchingFilters.size();
7451            for (int i = 0; i < size; i++) {
7452                CrossProfileIntentFilter filter = matchingFilters.get(i);
7453                int targetUserId = filter.getTargetUserId();
7454                boolean skipCurrentProfile =
7455                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7456                boolean skipCurrentProfileIfNoMatchFound =
7457                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7458                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7459                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7460                    // Checking if there are activities in the target user that can handle the
7461                    // intent.
7462                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7463                            resolvedType, flags, sourceUserId);
7464                    if (resolveInfo != null) return resolveInfo;
7465                    alreadyTriedUserIds.put(targetUserId, true);
7466                }
7467            }
7468        }
7469        return null;
7470    }
7471
7472    /**
7473     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7474     * will forward the intent to the filter's target user.
7475     * Otherwise, returns null.
7476     */
7477    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7478            String resolvedType, int flags, int sourceUserId) {
7479        int targetUserId = filter.getTargetUserId();
7480        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7481                resolvedType, flags, targetUserId);
7482        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7483            // If all the matches in the target profile are suspended, return null.
7484            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7485                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7486                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7487                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7488                            targetUserId);
7489                }
7490            }
7491        }
7492        return null;
7493    }
7494
7495    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7496            int sourceUserId, int targetUserId) {
7497        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7498        long ident = Binder.clearCallingIdentity();
7499        boolean targetIsProfile;
7500        try {
7501            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7502        } finally {
7503            Binder.restoreCallingIdentity(ident);
7504        }
7505        String className;
7506        if (targetIsProfile) {
7507            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7508        } else {
7509            className = FORWARD_INTENT_TO_PARENT;
7510        }
7511        ComponentName forwardingActivityComponentName = new ComponentName(
7512                mAndroidApplication.packageName, className);
7513        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7514                sourceUserId);
7515        if (!targetIsProfile) {
7516            forwardingActivityInfo.showUserIcon = targetUserId;
7517            forwardingResolveInfo.noResourceId = true;
7518        }
7519        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7520        forwardingResolveInfo.priority = 0;
7521        forwardingResolveInfo.preferredOrder = 0;
7522        forwardingResolveInfo.match = 0;
7523        forwardingResolveInfo.isDefault = true;
7524        forwardingResolveInfo.filter = filter;
7525        forwardingResolveInfo.targetUserId = targetUserId;
7526        return forwardingResolveInfo;
7527    }
7528
7529    @Override
7530    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7531            Intent[] specifics, String[] specificTypes, Intent intent,
7532            String resolvedType, int flags, int userId) {
7533        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7534                specificTypes, intent, resolvedType, flags, userId));
7535    }
7536
7537    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7538            Intent[] specifics, String[] specificTypes, Intent intent,
7539            String resolvedType, int flags, int userId) {
7540        if (!sUserManager.exists(userId)) return Collections.emptyList();
7541        final int callingUid = Binder.getCallingUid();
7542        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7543                false /*includeInstantApps*/);
7544        enforceCrossUserPermission(callingUid, userId,
7545                false /*requireFullPermission*/, false /*checkShell*/,
7546                "query intent activity options");
7547        final String resultsAction = intent.getAction();
7548
7549        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7550                | PackageManager.GET_RESOLVED_FILTER, userId);
7551
7552        if (DEBUG_INTENT_MATCHING) {
7553            Log.v(TAG, "Query " + intent + ": " + results);
7554        }
7555
7556        int specificsPos = 0;
7557        int N;
7558
7559        // todo: note that the algorithm used here is O(N^2).  This
7560        // isn't a problem in our current environment, but if we start running
7561        // into situations where we have more than 5 or 10 matches then this
7562        // should probably be changed to something smarter...
7563
7564        // First we go through and resolve each of the specific items
7565        // that were supplied, taking care of removing any corresponding
7566        // duplicate items in the generic resolve list.
7567        if (specifics != null) {
7568            for (int i=0; i<specifics.length; i++) {
7569                final Intent sintent = specifics[i];
7570                if (sintent == null) {
7571                    continue;
7572                }
7573
7574                if (DEBUG_INTENT_MATCHING) {
7575                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7576                }
7577
7578                String action = sintent.getAction();
7579                if (resultsAction != null && resultsAction.equals(action)) {
7580                    // If this action was explicitly requested, then don't
7581                    // remove things that have it.
7582                    action = null;
7583                }
7584
7585                ResolveInfo ri = null;
7586                ActivityInfo ai = null;
7587
7588                ComponentName comp = sintent.getComponent();
7589                if (comp == null) {
7590                    ri = resolveIntent(
7591                        sintent,
7592                        specificTypes != null ? specificTypes[i] : null,
7593                            flags, userId);
7594                    if (ri == null) {
7595                        continue;
7596                    }
7597                    if (ri == mResolveInfo) {
7598                        // ACK!  Must do something better with this.
7599                    }
7600                    ai = ri.activityInfo;
7601                    comp = new ComponentName(ai.applicationInfo.packageName,
7602                            ai.name);
7603                } else {
7604                    ai = getActivityInfo(comp, flags, userId);
7605                    if (ai == null) {
7606                        continue;
7607                    }
7608                }
7609
7610                // Look for any generic query activities that are duplicates
7611                // of this specific one, and remove them from the results.
7612                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7613                N = results.size();
7614                int j;
7615                for (j=specificsPos; j<N; j++) {
7616                    ResolveInfo sri = results.get(j);
7617                    if ((sri.activityInfo.name.equals(comp.getClassName())
7618                            && sri.activityInfo.applicationInfo.packageName.equals(
7619                                    comp.getPackageName()))
7620                        || (action != null && sri.filter.matchAction(action))) {
7621                        results.remove(j);
7622                        if (DEBUG_INTENT_MATCHING) Log.v(
7623                            TAG, "Removing duplicate item from " + j
7624                            + " due to specific " + specificsPos);
7625                        if (ri == null) {
7626                            ri = sri;
7627                        }
7628                        j--;
7629                        N--;
7630                    }
7631                }
7632
7633                // Add this specific item to its proper place.
7634                if (ri == null) {
7635                    ri = new ResolveInfo();
7636                    ri.activityInfo = ai;
7637                }
7638                results.add(specificsPos, ri);
7639                ri.specificIndex = i;
7640                specificsPos++;
7641            }
7642        }
7643
7644        // Now we go through the remaining generic results and remove any
7645        // duplicate actions that are found here.
7646        N = results.size();
7647        for (int i=specificsPos; i<N-1; i++) {
7648            final ResolveInfo rii = results.get(i);
7649            if (rii.filter == null) {
7650                continue;
7651            }
7652
7653            // Iterate over all of the actions of this result's intent
7654            // filter...  typically this should be just one.
7655            final Iterator<String> it = rii.filter.actionsIterator();
7656            if (it == null) {
7657                continue;
7658            }
7659            while (it.hasNext()) {
7660                final String action = it.next();
7661                if (resultsAction != null && resultsAction.equals(action)) {
7662                    // If this action was explicitly requested, then don't
7663                    // remove things that have it.
7664                    continue;
7665                }
7666                for (int j=i+1; j<N; j++) {
7667                    final ResolveInfo rij = results.get(j);
7668                    if (rij.filter != null && rij.filter.hasAction(action)) {
7669                        results.remove(j);
7670                        if (DEBUG_INTENT_MATCHING) Log.v(
7671                            TAG, "Removing duplicate item from " + j
7672                            + " due to action " + action + " at " + i);
7673                        j--;
7674                        N--;
7675                    }
7676                }
7677            }
7678
7679            // If the caller didn't request filter information, drop it now
7680            // so we don't have to marshall/unmarshall it.
7681            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7682                rii.filter = null;
7683            }
7684        }
7685
7686        // Filter out the caller activity if so requested.
7687        if (caller != null) {
7688            N = results.size();
7689            for (int i=0; i<N; i++) {
7690                ActivityInfo ainfo = results.get(i).activityInfo;
7691                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7692                        && caller.getClassName().equals(ainfo.name)) {
7693                    results.remove(i);
7694                    break;
7695                }
7696            }
7697        }
7698
7699        // If the caller didn't request filter information,
7700        // drop them now so we don't have to
7701        // marshall/unmarshall it.
7702        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7703            N = results.size();
7704            for (int i=0; i<N; i++) {
7705                results.get(i).filter = null;
7706            }
7707        }
7708
7709        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7710        return results;
7711    }
7712
7713    @Override
7714    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7715            String resolvedType, int flags, int userId) {
7716        return new ParceledListSlice<>(
7717                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7718    }
7719
7720    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7721            String resolvedType, int flags, int userId) {
7722        if (!sUserManager.exists(userId)) return Collections.emptyList();
7723        final int callingUid = Binder.getCallingUid();
7724        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7725        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7726                false /*includeInstantApps*/);
7727        ComponentName comp = intent.getComponent();
7728        if (comp == null) {
7729            if (intent.getSelector() != null) {
7730                intent = intent.getSelector();
7731                comp = intent.getComponent();
7732            }
7733        }
7734        if (comp != null) {
7735            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7736            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7737            if (ai != null) {
7738                // When specifying an explicit component, we prevent the activity from being
7739                // used when either 1) the calling package is normal and the activity is within
7740                // an instant application or 2) the calling package is ephemeral and the
7741                // activity is not visible to instant applications.
7742                final boolean matchInstantApp =
7743                        (flags & PackageManager.MATCH_INSTANT) != 0;
7744                final boolean matchVisibleToInstantAppOnly =
7745                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7746                final boolean matchExplicitlyVisibleOnly =
7747                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7748                final boolean isCallerInstantApp =
7749                        instantAppPkgName != null;
7750                final boolean isTargetSameInstantApp =
7751                        comp.getPackageName().equals(instantAppPkgName);
7752                final boolean isTargetInstantApp =
7753                        (ai.applicationInfo.privateFlags
7754                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7755                final boolean isTargetVisibleToInstantApp =
7756                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7757                final boolean isTargetExplicitlyVisibleToInstantApp =
7758                        isTargetVisibleToInstantApp
7759                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7760                final boolean isTargetHiddenFromInstantApp =
7761                        !isTargetVisibleToInstantApp
7762                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7763                final boolean blockResolution =
7764                        !isTargetSameInstantApp
7765                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7766                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7767                                        && isTargetHiddenFromInstantApp));
7768                if (!blockResolution) {
7769                    ResolveInfo ri = new ResolveInfo();
7770                    ri.activityInfo = ai;
7771                    list.add(ri);
7772                }
7773            }
7774            return applyPostResolutionFilter(list, instantAppPkgName);
7775        }
7776
7777        // reader
7778        synchronized (mPackages) {
7779            String pkgName = intent.getPackage();
7780            if (pkgName == null) {
7781                final List<ResolveInfo> result =
7782                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7783                return applyPostResolutionFilter(result, instantAppPkgName);
7784            }
7785            final PackageParser.Package pkg = mPackages.get(pkgName);
7786            if (pkg != null) {
7787                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7788                        intent, resolvedType, flags, pkg.receivers, userId);
7789                return applyPostResolutionFilter(result, instantAppPkgName);
7790            }
7791            return Collections.emptyList();
7792        }
7793    }
7794
7795    @Override
7796    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7797        final int callingUid = Binder.getCallingUid();
7798        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7799    }
7800
7801    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7802            int userId, int callingUid) {
7803        if (!sUserManager.exists(userId)) return null;
7804        flags = updateFlagsForResolve(
7805                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7806        List<ResolveInfo> query = queryIntentServicesInternal(
7807                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7808        if (query != null) {
7809            if (query.size() >= 1) {
7810                // If there is more than one service with the same priority,
7811                // just arbitrarily pick the first one.
7812                return query.get(0);
7813            }
7814        }
7815        return null;
7816    }
7817
7818    @Override
7819    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7820            String resolvedType, int flags, int userId) {
7821        final int callingUid = Binder.getCallingUid();
7822        return new ParceledListSlice<>(queryIntentServicesInternal(
7823                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7824    }
7825
7826    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7827            String resolvedType, int flags, int userId, int callingUid,
7828            boolean includeInstantApps) {
7829        if (!sUserManager.exists(userId)) return Collections.emptyList();
7830        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7831        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7832        ComponentName comp = intent.getComponent();
7833        if (comp == null) {
7834            if (intent.getSelector() != null) {
7835                intent = intent.getSelector();
7836                comp = intent.getComponent();
7837            }
7838        }
7839        if (comp != null) {
7840            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7841            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7842            if (si != null) {
7843                // When specifying an explicit component, we prevent the service from being
7844                // used when either 1) the service is in an instant application and the
7845                // caller is not the same instant application or 2) the calling package is
7846                // ephemeral and the activity is not visible to ephemeral applications.
7847                final boolean matchInstantApp =
7848                        (flags & PackageManager.MATCH_INSTANT) != 0;
7849                final boolean matchVisibleToInstantAppOnly =
7850                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7851                final boolean isCallerInstantApp =
7852                        instantAppPkgName != null;
7853                final boolean isTargetSameInstantApp =
7854                        comp.getPackageName().equals(instantAppPkgName);
7855                final boolean isTargetInstantApp =
7856                        (si.applicationInfo.privateFlags
7857                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7858                final boolean isTargetHiddenFromInstantApp =
7859                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7860                final boolean blockResolution =
7861                        !isTargetSameInstantApp
7862                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7863                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7864                                        && isTargetHiddenFromInstantApp));
7865                if (!blockResolution) {
7866                    final ResolveInfo ri = new ResolveInfo();
7867                    ri.serviceInfo = si;
7868                    list.add(ri);
7869                }
7870            }
7871            return list;
7872        }
7873
7874        // reader
7875        synchronized (mPackages) {
7876            String pkgName = intent.getPackage();
7877            if (pkgName == null) {
7878                return applyPostServiceResolutionFilter(
7879                        mServices.queryIntent(intent, resolvedType, flags, userId),
7880                        instantAppPkgName);
7881            }
7882            final PackageParser.Package pkg = mPackages.get(pkgName);
7883            if (pkg != null) {
7884                return applyPostServiceResolutionFilter(
7885                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7886                                userId),
7887                        instantAppPkgName);
7888            }
7889            return Collections.emptyList();
7890        }
7891    }
7892
7893    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7894            String instantAppPkgName) {
7895        // TODO: When adding on-demand split support for non-instant apps, remove this check
7896        // and always apply post filtering
7897        if (instantAppPkgName == null) {
7898            return resolveInfos;
7899        }
7900        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7901            final ResolveInfo info = resolveInfos.get(i);
7902            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7903            // allow services that are defined in the provided package
7904            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7905                if (info.serviceInfo.splitName != null
7906                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7907                                info.serviceInfo.splitName)) {
7908                    // requested service is defined in a split that hasn't been installed yet.
7909                    // add the installer to the resolve list
7910                    if (DEBUG_EPHEMERAL) {
7911                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7912                    }
7913                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7914                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7915                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7916                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7917                    // make sure this resolver is the default
7918                    installerInfo.isDefault = true;
7919                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7920                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7921                    // add a non-generic filter
7922                    installerInfo.filter = new IntentFilter();
7923                    // load resources from the correct package
7924                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7925                    resolveInfos.set(i, installerInfo);
7926                }
7927                continue;
7928            }
7929            // allow services that have been explicitly exposed to ephemeral apps
7930            if (!isEphemeralApp
7931                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7932                continue;
7933            }
7934            resolveInfos.remove(i);
7935        }
7936        return resolveInfos;
7937    }
7938
7939    @Override
7940    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7941            String resolvedType, int flags, int userId) {
7942        return new ParceledListSlice<>(
7943                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7944    }
7945
7946    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7947            Intent intent, String resolvedType, int flags, int userId) {
7948        if (!sUserManager.exists(userId)) return Collections.emptyList();
7949        final int callingUid = Binder.getCallingUid();
7950        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7951        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7952                false /*includeInstantApps*/);
7953        ComponentName comp = intent.getComponent();
7954        if (comp == null) {
7955            if (intent.getSelector() != null) {
7956                intent = intent.getSelector();
7957                comp = intent.getComponent();
7958            }
7959        }
7960        if (comp != null) {
7961            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7962            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7963            if (pi != null) {
7964                // When specifying an explicit component, we prevent the provider from being
7965                // used when either 1) the provider is in an instant application and the
7966                // caller is not the same instant application or 2) the calling package is an
7967                // instant application and the provider is not visible to instant applications.
7968                final boolean matchInstantApp =
7969                        (flags & PackageManager.MATCH_INSTANT) != 0;
7970                final boolean matchVisibleToInstantAppOnly =
7971                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7972                final boolean isCallerInstantApp =
7973                        instantAppPkgName != null;
7974                final boolean isTargetSameInstantApp =
7975                        comp.getPackageName().equals(instantAppPkgName);
7976                final boolean isTargetInstantApp =
7977                        (pi.applicationInfo.privateFlags
7978                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7979                final boolean isTargetHiddenFromInstantApp =
7980                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7981                final boolean blockResolution =
7982                        !isTargetSameInstantApp
7983                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7984                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7985                                        && isTargetHiddenFromInstantApp));
7986                if (!blockResolution) {
7987                    final ResolveInfo ri = new ResolveInfo();
7988                    ri.providerInfo = pi;
7989                    list.add(ri);
7990                }
7991            }
7992            return list;
7993        }
7994
7995        // reader
7996        synchronized (mPackages) {
7997            String pkgName = intent.getPackage();
7998            if (pkgName == null) {
7999                return applyPostContentProviderResolutionFilter(
8000                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8001                        instantAppPkgName);
8002            }
8003            final PackageParser.Package pkg = mPackages.get(pkgName);
8004            if (pkg != null) {
8005                return applyPostContentProviderResolutionFilter(
8006                        mProviders.queryIntentForPackage(
8007                        intent, resolvedType, flags, pkg.providers, userId),
8008                        instantAppPkgName);
8009            }
8010            return Collections.emptyList();
8011        }
8012    }
8013
8014    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8015            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8016        // TODO: When adding on-demand split support for non-instant applications, remove
8017        // this check and always apply post filtering
8018        if (instantAppPkgName == null) {
8019            return resolveInfos;
8020        }
8021        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8022            final ResolveInfo info = resolveInfos.get(i);
8023            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8024            // allow providers that are defined in the provided package
8025            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8026                if (info.providerInfo.splitName != null
8027                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8028                                info.providerInfo.splitName)) {
8029                    // requested provider is defined in a split that hasn't been installed yet.
8030                    // add the installer to the resolve list
8031                    if (DEBUG_EPHEMERAL) {
8032                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8033                    }
8034                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8035                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8036                            info.providerInfo.packageName, info.providerInfo.splitName,
8037                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8038                    // make sure this resolver is the default
8039                    installerInfo.isDefault = true;
8040                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8041                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8042                    // add a non-generic filter
8043                    installerInfo.filter = new IntentFilter();
8044                    // load resources from the correct package
8045                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8046                    resolveInfos.set(i, installerInfo);
8047                }
8048                continue;
8049            }
8050            // allow providers that have been explicitly exposed to instant applications
8051            if (!isEphemeralApp
8052                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8053                continue;
8054            }
8055            resolveInfos.remove(i);
8056        }
8057        return resolveInfos;
8058    }
8059
8060    @Override
8061    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8062        final int callingUid = Binder.getCallingUid();
8063        if (getInstantAppPackageName(callingUid) != null) {
8064            return ParceledListSlice.emptyList();
8065        }
8066        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8067        flags = updateFlagsForPackage(flags, userId, null);
8068        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8069        enforceCrossUserPermission(callingUid, userId,
8070                true /* requireFullPermission */, false /* checkShell */,
8071                "get installed packages");
8072
8073        // writer
8074        synchronized (mPackages) {
8075            ArrayList<PackageInfo> list;
8076            if (listUninstalled) {
8077                list = new ArrayList<>(mSettings.mPackages.size());
8078                for (PackageSetting ps : mSettings.mPackages.values()) {
8079                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8080                        continue;
8081                    }
8082                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8083                        return null;
8084                    }
8085                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8086                    if (pi != null) {
8087                        list.add(pi);
8088                    }
8089                }
8090            } else {
8091                list = new ArrayList<>(mPackages.size());
8092                for (PackageParser.Package p : mPackages.values()) {
8093                    final PackageSetting ps = (PackageSetting) p.mExtras;
8094                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8095                        continue;
8096                    }
8097                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8098                        return null;
8099                    }
8100                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8101                            p.mExtras, flags, userId);
8102                    if (pi != null) {
8103                        list.add(pi);
8104                    }
8105                }
8106            }
8107
8108            return new ParceledListSlice<>(list);
8109        }
8110    }
8111
8112    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8113            String[] permissions, boolean[] tmp, int flags, int userId) {
8114        int numMatch = 0;
8115        final PermissionsState permissionsState = ps.getPermissionsState();
8116        for (int i=0; i<permissions.length; i++) {
8117            final String permission = permissions[i];
8118            if (permissionsState.hasPermission(permission, userId)) {
8119                tmp[i] = true;
8120                numMatch++;
8121            } else {
8122                tmp[i] = false;
8123            }
8124        }
8125        if (numMatch == 0) {
8126            return;
8127        }
8128        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8129
8130        // The above might return null in cases of uninstalled apps or install-state
8131        // skew across users/profiles.
8132        if (pi != null) {
8133            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8134                if (numMatch == permissions.length) {
8135                    pi.requestedPermissions = permissions;
8136                } else {
8137                    pi.requestedPermissions = new String[numMatch];
8138                    numMatch = 0;
8139                    for (int i=0; i<permissions.length; i++) {
8140                        if (tmp[i]) {
8141                            pi.requestedPermissions[numMatch] = permissions[i];
8142                            numMatch++;
8143                        }
8144                    }
8145                }
8146            }
8147            list.add(pi);
8148        }
8149    }
8150
8151    @Override
8152    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8153            String[] permissions, int flags, int userId) {
8154        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8155        flags = updateFlagsForPackage(flags, userId, permissions);
8156        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8157                true /* requireFullPermission */, false /* checkShell */,
8158                "get packages holding permissions");
8159        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8160
8161        // writer
8162        synchronized (mPackages) {
8163            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8164            boolean[] tmpBools = new boolean[permissions.length];
8165            if (listUninstalled) {
8166                for (PackageSetting ps : mSettings.mPackages.values()) {
8167                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8168                            userId);
8169                }
8170            } else {
8171                for (PackageParser.Package pkg : mPackages.values()) {
8172                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8173                    if (ps != null) {
8174                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8175                                userId);
8176                    }
8177                }
8178            }
8179
8180            return new ParceledListSlice<PackageInfo>(list);
8181        }
8182    }
8183
8184    @Override
8185    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8186        final int callingUid = Binder.getCallingUid();
8187        if (getInstantAppPackageName(callingUid) != null) {
8188            return ParceledListSlice.emptyList();
8189        }
8190        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8191        flags = updateFlagsForApplication(flags, userId, null);
8192        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8193
8194        // writer
8195        synchronized (mPackages) {
8196            ArrayList<ApplicationInfo> list;
8197            if (listUninstalled) {
8198                list = new ArrayList<>(mSettings.mPackages.size());
8199                for (PackageSetting ps : mSettings.mPackages.values()) {
8200                    ApplicationInfo ai;
8201                    int effectiveFlags = flags;
8202                    if (ps.isSystem()) {
8203                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8204                    }
8205                    if (ps.pkg != null) {
8206                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8207                            continue;
8208                        }
8209                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8210                            return null;
8211                        }
8212                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8213                                ps.readUserState(userId), userId);
8214                        if (ai != null) {
8215                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8216                        }
8217                    } else {
8218                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8219                        // and already converts to externally visible package name
8220                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8221                                callingUid, effectiveFlags, userId);
8222                    }
8223                    if (ai != null) {
8224                        list.add(ai);
8225                    }
8226                }
8227            } else {
8228                list = new ArrayList<>(mPackages.size());
8229                for (PackageParser.Package p : mPackages.values()) {
8230                    if (p.mExtras != null) {
8231                        PackageSetting ps = (PackageSetting) p.mExtras;
8232                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8233                            continue;
8234                        }
8235                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8236                            return null;
8237                        }
8238                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8239                                ps.readUserState(userId), userId);
8240                        if (ai != null) {
8241                            ai.packageName = resolveExternalPackageNameLPr(p);
8242                            list.add(ai);
8243                        }
8244                    }
8245                }
8246            }
8247
8248            return new ParceledListSlice<>(list);
8249        }
8250    }
8251
8252    @Override
8253    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8254        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8255            return null;
8256        }
8257        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8258                "getEphemeralApplications");
8259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8260                true /* requireFullPermission */, false /* checkShell */,
8261                "getEphemeralApplications");
8262        synchronized (mPackages) {
8263            List<InstantAppInfo> instantApps = mInstantAppRegistry
8264                    .getInstantAppsLPr(userId);
8265            if (instantApps != null) {
8266                return new ParceledListSlice<>(instantApps);
8267            }
8268        }
8269        return null;
8270    }
8271
8272    @Override
8273    public boolean isInstantApp(String packageName, int userId) {
8274        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8275                true /* requireFullPermission */, false /* checkShell */,
8276                "isInstantApp");
8277        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8278            return false;
8279        }
8280        int callingUid = Binder.getCallingUid();
8281        if (Process.isIsolated(callingUid)) {
8282            callingUid = mIsolatedOwners.get(callingUid);
8283        }
8284
8285        synchronized (mPackages) {
8286            final PackageSetting ps = mSettings.mPackages.get(packageName);
8287            PackageParser.Package pkg = mPackages.get(packageName);
8288            final boolean returnAllowed =
8289                    ps != null
8290                    && (isCallerSameApp(packageName, callingUid)
8291                            || canViewInstantApps(callingUid, userId)
8292                            || mInstantAppRegistry.isInstantAccessGranted(
8293                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8294            if (returnAllowed) {
8295                return ps.getInstantApp(userId);
8296            }
8297        }
8298        return false;
8299    }
8300
8301    @Override
8302    public byte[] getInstantAppCookie(String packageName, int userId) {
8303        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8304            return null;
8305        }
8306
8307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8308                true /* requireFullPermission */, false /* checkShell */,
8309                "getInstantAppCookie");
8310        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8311            return null;
8312        }
8313        synchronized (mPackages) {
8314            return mInstantAppRegistry.getInstantAppCookieLPw(
8315                    packageName, userId);
8316        }
8317    }
8318
8319    @Override
8320    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8321        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8322            return true;
8323        }
8324
8325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8326                true /* requireFullPermission */, true /* checkShell */,
8327                "setInstantAppCookie");
8328        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8329            return false;
8330        }
8331        synchronized (mPackages) {
8332            return mInstantAppRegistry.setInstantAppCookieLPw(
8333                    packageName, cookie, userId);
8334        }
8335    }
8336
8337    @Override
8338    public Bitmap getInstantAppIcon(String packageName, int userId) {
8339        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8340            return null;
8341        }
8342
8343        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8344                "getInstantAppIcon");
8345
8346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8347                true /* requireFullPermission */, false /* checkShell */,
8348                "getInstantAppIcon");
8349
8350        synchronized (mPackages) {
8351            return mInstantAppRegistry.getInstantAppIconLPw(
8352                    packageName, userId);
8353        }
8354    }
8355
8356    private boolean isCallerSameApp(String packageName, int uid) {
8357        PackageParser.Package pkg = mPackages.get(packageName);
8358        return pkg != null
8359                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8360    }
8361
8362    @Override
8363    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8364        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8365            return ParceledListSlice.emptyList();
8366        }
8367        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8368    }
8369
8370    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8371        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8372
8373        // reader
8374        synchronized (mPackages) {
8375            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8376            final int userId = UserHandle.getCallingUserId();
8377            while (i.hasNext()) {
8378                final PackageParser.Package p = i.next();
8379                if (p.applicationInfo == null) continue;
8380
8381                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8382                        && !p.applicationInfo.isDirectBootAware();
8383                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8384                        && p.applicationInfo.isDirectBootAware();
8385
8386                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8387                        && (!mSafeMode || isSystemApp(p))
8388                        && (matchesUnaware || matchesAware)) {
8389                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8390                    if (ps != null) {
8391                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8392                                ps.readUserState(userId), userId);
8393                        if (ai != null) {
8394                            finalList.add(ai);
8395                        }
8396                    }
8397                }
8398            }
8399        }
8400
8401        return finalList;
8402    }
8403
8404    @Override
8405    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8406        if (!sUserManager.exists(userId)) return null;
8407        flags = updateFlagsForComponent(flags, userId, name);
8408        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8409        // reader
8410        synchronized (mPackages) {
8411            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8412            PackageSetting ps = provider != null
8413                    ? mSettings.mPackages.get(provider.owner.packageName)
8414                    : null;
8415            if (ps != null) {
8416                final boolean isInstantApp = ps.getInstantApp(userId);
8417                // normal application; filter out instant application provider
8418                if (instantAppPkgName == null && isInstantApp) {
8419                    return null;
8420                }
8421                // instant application; filter out other instant applications
8422                if (instantAppPkgName != null
8423                        && isInstantApp
8424                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8425                    return null;
8426                }
8427                // instant application; filter out non-exposed provider
8428                if (instantAppPkgName != null
8429                        && !isInstantApp
8430                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8431                    return null;
8432                }
8433                // provider not enabled
8434                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8435                    return null;
8436                }
8437                return PackageParser.generateProviderInfo(
8438                        provider, flags, ps.readUserState(userId), userId);
8439            }
8440            return null;
8441        }
8442    }
8443
8444    /**
8445     * @deprecated
8446     */
8447    @Deprecated
8448    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8449        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8450            return;
8451        }
8452        // reader
8453        synchronized (mPackages) {
8454            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8455                    .entrySet().iterator();
8456            final int userId = UserHandle.getCallingUserId();
8457            while (i.hasNext()) {
8458                Map.Entry<String, PackageParser.Provider> entry = i.next();
8459                PackageParser.Provider p = entry.getValue();
8460                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8461
8462                if (ps != null && p.syncable
8463                        && (!mSafeMode || (p.info.applicationInfo.flags
8464                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8465                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8466                            ps.readUserState(userId), userId);
8467                    if (info != null) {
8468                        outNames.add(entry.getKey());
8469                        outInfo.add(info);
8470                    }
8471                }
8472            }
8473        }
8474    }
8475
8476    @Override
8477    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8478            int uid, int flags, String metaDataKey) {
8479        final int callingUid = Binder.getCallingUid();
8480        final int userId = processName != null ? UserHandle.getUserId(uid)
8481                : UserHandle.getCallingUserId();
8482        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8483        flags = updateFlagsForComponent(flags, userId, processName);
8484        ArrayList<ProviderInfo> finalList = null;
8485        // reader
8486        synchronized (mPackages) {
8487            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8488            while (i.hasNext()) {
8489                final PackageParser.Provider p = i.next();
8490                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8491                if (ps != null && p.info.authority != null
8492                        && (processName == null
8493                                || (p.info.processName.equals(processName)
8494                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8495                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8496
8497                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8498                    // parameter.
8499                    if (metaDataKey != null
8500                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8501                        continue;
8502                    }
8503                    final ComponentName component =
8504                            new ComponentName(p.info.packageName, p.info.name);
8505                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8506                        continue;
8507                    }
8508                    if (finalList == null) {
8509                        finalList = new ArrayList<ProviderInfo>(3);
8510                    }
8511                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8512                            ps.readUserState(userId), userId);
8513                    if (info != null) {
8514                        finalList.add(info);
8515                    }
8516                }
8517            }
8518        }
8519
8520        if (finalList != null) {
8521            Collections.sort(finalList, mProviderInitOrderSorter);
8522            return new ParceledListSlice<ProviderInfo>(finalList);
8523        }
8524
8525        return ParceledListSlice.emptyList();
8526    }
8527
8528    @Override
8529    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8530        // reader
8531        synchronized (mPackages) {
8532            final int callingUid = Binder.getCallingUid();
8533            final int callingUserId = UserHandle.getUserId(callingUid);
8534            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8535            if (ps == null) return null;
8536            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8537                return null;
8538            }
8539            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8540            return PackageParser.generateInstrumentationInfo(i, flags);
8541        }
8542    }
8543
8544    @Override
8545    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8546            String targetPackage, int flags) {
8547        final int callingUid = Binder.getCallingUid();
8548        final int callingUserId = UserHandle.getUserId(callingUid);
8549        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8550        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8551            return ParceledListSlice.emptyList();
8552        }
8553        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8554    }
8555
8556    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8557            int flags) {
8558        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8559
8560        // reader
8561        synchronized (mPackages) {
8562            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8563            while (i.hasNext()) {
8564                final PackageParser.Instrumentation p = i.next();
8565                if (targetPackage == null
8566                        || targetPackage.equals(p.info.targetPackage)) {
8567                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8568                            flags);
8569                    if (ii != null) {
8570                        finalList.add(ii);
8571                    }
8572                }
8573            }
8574        }
8575
8576        return finalList;
8577    }
8578
8579    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8580        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8581        try {
8582            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8583        } finally {
8584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8585        }
8586    }
8587
8588    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8589        final File[] files = dir.listFiles();
8590        if (ArrayUtils.isEmpty(files)) {
8591            Log.d(TAG, "No files in app dir " + dir);
8592            return;
8593        }
8594
8595        if (DEBUG_PACKAGE_SCANNING) {
8596            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8597                    + " flags=0x" + Integer.toHexString(parseFlags));
8598        }
8599        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8600                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8601                mParallelPackageParserCallback);
8602
8603        // Submit files for parsing in parallel
8604        int fileCount = 0;
8605        for (File file : files) {
8606            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8607                    && !PackageInstallerService.isStageName(file.getName());
8608            if (!isPackage) {
8609                // Ignore entries which are not packages
8610                continue;
8611            }
8612            parallelPackageParser.submit(file, parseFlags);
8613            fileCount++;
8614        }
8615
8616        // Process results one by one
8617        for (; fileCount > 0; fileCount--) {
8618            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8619            Throwable throwable = parseResult.throwable;
8620            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8621
8622            if (throwable == null) {
8623                // Static shared libraries have synthetic package names
8624                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8625                    renameStaticSharedLibraryPackage(parseResult.pkg);
8626                }
8627                try {
8628                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8629                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8630                                currentTime, null);
8631                    }
8632                } catch (PackageManagerException e) {
8633                    errorCode = e.error;
8634                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8635                }
8636            } else if (throwable instanceof PackageParser.PackageParserException) {
8637                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8638                        throwable;
8639                errorCode = e.error;
8640                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8641            } else {
8642                throw new IllegalStateException("Unexpected exception occurred while parsing "
8643                        + parseResult.scanFile, throwable);
8644            }
8645
8646            // Delete invalid userdata apps
8647            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8648                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8649                logCriticalInfo(Log.WARN,
8650                        "Deleting invalid package at " + parseResult.scanFile);
8651                removeCodePathLI(parseResult.scanFile);
8652            }
8653        }
8654        parallelPackageParser.close();
8655    }
8656
8657    private static File getSettingsProblemFile() {
8658        File dataDir = Environment.getDataDirectory();
8659        File systemDir = new File(dataDir, "system");
8660        File fname = new File(systemDir, "uiderrors.txt");
8661        return fname;
8662    }
8663
8664    static void reportSettingsProblem(int priority, String msg) {
8665        logCriticalInfo(priority, msg);
8666    }
8667
8668    public static void logCriticalInfo(int priority, String msg) {
8669        Slog.println(priority, TAG, msg);
8670        EventLogTags.writePmCriticalInfo(msg);
8671        try {
8672            File fname = getSettingsProblemFile();
8673            FileOutputStream out = new FileOutputStream(fname, true);
8674            PrintWriter pw = new FastPrintWriter(out);
8675            SimpleDateFormat formatter = new SimpleDateFormat();
8676            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8677            pw.println(dateString + ": " + msg);
8678            pw.close();
8679            FileUtils.setPermissions(
8680                    fname.toString(),
8681                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8682                    -1, -1);
8683        } catch (java.io.IOException e) {
8684        }
8685    }
8686
8687    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8688        if (srcFile.isDirectory()) {
8689            final File baseFile = new File(pkg.baseCodePath);
8690            long maxModifiedTime = baseFile.lastModified();
8691            if (pkg.splitCodePaths != null) {
8692                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8693                    final File splitFile = new File(pkg.splitCodePaths[i]);
8694                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8695                }
8696            }
8697            return maxModifiedTime;
8698        }
8699        return srcFile.lastModified();
8700    }
8701
8702    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8703            final int policyFlags) throws PackageManagerException {
8704        // When upgrading from pre-N MR1, verify the package time stamp using the package
8705        // directory and not the APK file.
8706        final long lastModifiedTime = mIsPreNMR1Upgrade
8707                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8708        if (ps != null
8709                && ps.codePath.equals(srcFile)
8710                && ps.timeStamp == lastModifiedTime
8711                && !isCompatSignatureUpdateNeeded(pkg)
8712                && !isRecoverSignatureUpdateNeeded(pkg)) {
8713            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8714            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8715            ArraySet<PublicKey> signingKs;
8716            synchronized (mPackages) {
8717                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8718            }
8719            if (ps.signatures.mSignatures != null
8720                    && ps.signatures.mSignatures.length != 0
8721                    && signingKs != null) {
8722                // Optimization: reuse the existing cached certificates
8723                // if the package appears to be unchanged.
8724                pkg.mSignatures = ps.signatures.mSignatures;
8725                pkg.mSigningKeys = signingKs;
8726                return;
8727            }
8728
8729            Slog.w(TAG, "PackageSetting for " + ps.name
8730                    + " is missing signatures.  Collecting certs again to recover them.");
8731        } else {
8732            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8733        }
8734
8735        try {
8736            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8737            PackageParser.collectCertificates(pkg, policyFlags);
8738        } catch (PackageParserException e) {
8739            throw PackageManagerException.from(e);
8740        } finally {
8741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8742        }
8743    }
8744
8745    /**
8746     *  Traces a package scan.
8747     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8748     */
8749    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8750            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8751        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8752        try {
8753            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8754        } finally {
8755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8756        }
8757    }
8758
8759    /**
8760     *  Scans a package and returns the newly parsed package.
8761     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8762     */
8763    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8764            long currentTime, UserHandle user) throws PackageManagerException {
8765        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8766        PackageParser pp = new PackageParser();
8767        pp.setSeparateProcesses(mSeparateProcesses);
8768        pp.setOnlyCoreApps(mOnlyCore);
8769        pp.setDisplayMetrics(mMetrics);
8770        pp.setCallback(mPackageParserCallback);
8771
8772        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8773            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8774        }
8775
8776        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8777        final PackageParser.Package pkg;
8778        try {
8779            pkg = pp.parsePackage(scanFile, parseFlags);
8780        } catch (PackageParserException e) {
8781            throw PackageManagerException.from(e);
8782        } finally {
8783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8784        }
8785
8786        // Static shared libraries have synthetic package names
8787        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8788            renameStaticSharedLibraryPackage(pkg);
8789        }
8790
8791        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8792    }
8793
8794    /**
8795     *  Scans a package and returns the newly parsed package.
8796     *  @throws PackageManagerException on a parse error.
8797     */
8798    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8799            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8800            throws PackageManagerException {
8801        // If the package has children and this is the first dive in the function
8802        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8803        // packages (parent and children) would be successfully scanned before the
8804        // actual scan since scanning mutates internal state and we want to atomically
8805        // install the package and its children.
8806        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8807            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8808                scanFlags |= SCAN_CHECK_ONLY;
8809            }
8810        } else {
8811            scanFlags &= ~SCAN_CHECK_ONLY;
8812        }
8813
8814        // Scan the parent
8815        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8816                scanFlags, currentTime, user);
8817
8818        // Scan the children
8819        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8820        for (int i = 0; i < childCount; i++) {
8821            PackageParser.Package childPackage = pkg.childPackages.get(i);
8822            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8823                    currentTime, user);
8824        }
8825
8826
8827        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8828            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8829        }
8830
8831        return scannedPkg;
8832    }
8833
8834    /**
8835     *  Scans a package and returns the newly parsed package.
8836     *  @throws PackageManagerException on a parse error.
8837     */
8838    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8839            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8840            throws PackageManagerException {
8841        PackageSetting ps = null;
8842        PackageSetting updatedPkg;
8843        // reader
8844        synchronized (mPackages) {
8845            // Look to see if we already know about this package.
8846            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8847            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8848                // This package has been renamed to its original name.  Let's
8849                // use that.
8850                ps = mSettings.getPackageLPr(oldName);
8851            }
8852            // If there was no original package, see one for the real package name.
8853            if (ps == null) {
8854                ps = mSettings.getPackageLPr(pkg.packageName);
8855            }
8856            // Check to see if this package could be hiding/updating a system
8857            // package.  Must look for it either under the original or real
8858            // package name depending on our state.
8859            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8860            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8861
8862            // If this is a package we don't know about on the system partition, we
8863            // may need to remove disabled child packages on the system partition
8864            // or may need to not add child packages if the parent apk is updated
8865            // on the data partition and no longer defines this child package.
8866            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8867                // If this is a parent package for an updated system app and this system
8868                // app got an OTA update which no longer defines some of the child packages
8869                // we have to prune them from the disabled system packages.
8870                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8871                if (disabledPs != null) {
8872                    final int scannedChildCount = (pkg.childPackages != null)
8873                            ? pkg.childPackages.size() : 0;
8874                    final int disabledChildCount = disabledPs.childPackageNames != null
8875                            ? disabledPs.childPackageNames.size() : 0;
8876                    for (int i = 0; i < disabledChildCount; i++) {
8877                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8878                        boolean disabledPackageAvailable = false;
8879                        for (int j = 0; j < scannedChildCount; j++) {
8880                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8881                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8882                                disabledPackageAvailable = true;
8883                                break;
8884                            }
8885                         }
8886                         if (!disabledPackageAvailable) {
8887                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8888                         }
8889                    }
8890                }
8891            }
8892        }
8893
8894        boolean updatedPkgBetter = false;
8895        // First check if this is a system package that may involve an update
8896        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8897            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8898            // it needs to drop FLAG_PRIVILEGED.
8899            if (locationIsPrivileged(scanFile)) {
8900                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8901            } else {
8902                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8903            }
8904
8905            if (ps != null && !ps.codePath.equals(scanFile)) {
8906                // The path has changed from what was last scanned...  check the
8907                // version of the new path against what we have stored to determine
8908                // what to do.
8909                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8910                if (pkg.mVersionCode <= ps.versionCode) {
8911                    // The system package has been updated and the code path does not match
8912                    // Ignore entry. Skip it.
8913                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8914                            + " ignored: updated version " + ps.versionCode
8915                            + " better than this " + pkg.mVersionCode);
8916                    if (!updatedPkg.codePath.equals(scanFile)) {
8917                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8918                                + ps.name + " changing from " + updatedPkg.codePathString
8919                                + " to " + scanFile);
8920                        updatedPkg.codePath = scanFile;
8921                        updatedPkg.codePathString = scanFile.toString();
8922                        updatedPkg.resourcePath = scanFile;
8923                        updatedPkg.resourcePathString = scanFile.toString();
8924                    }
8925                    updatedPkg.pkg = pkg;
8926                    updatedPkg.versionCode = pkg.mVersionCode;
8927
8928                    // Update the disabled system child packages to point to the package too.
8929                    final int childCount = updatedPkg.childPackageNames != null
8930                            ? updatedPkg.childPackageNames.size() : 0;
8931                    for (int i = 0; i < childCount; i++) {
8932                        String childPackageName = updatedPkg.childPackageNames.get(i);
8933                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8934                                childPackageName);
8935                        if (updatedChildPkg != null) {
8936                            updatedChildPkg.pkg = pkg;
8937                            updatedChildPkg.versionCode = pkg.mVersionCode;
8938                        }
8939                    }
8940
8941                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8942                            + scanFile + " ignored: updated version " + ps.versionCode
8943                            + " better than this " + pkg.mVersionCode);
8944                } else {
8945                    // The current app on the system partition is better than
8946                    // what we have updated to on the data partition; switch
8947                    // back to the system partition version.
8948                    // At this point, its safely assumed that package installation for
8949                    // apps in system partition will go through. If not there won't be a working
8950                    // version of the app
8951                    // writer
8952                    synchronized (mPackages) {
8953                        // Just remove the loaded entries from package lists.
8954                        mPackages.remove(ps.name);
8955                    }
8956
8957                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8958                            + " reverting from " + ps.codePathString
8959                            + ": new version " + pkg.mVersionCode
8960                            + " better than installed " + ps.versionCode);
8961
8962                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8963                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8964                    synchronized (mInstallLock) {
8965                        args.cleanUpResourcesLI();
8966                    }
8967                    synchronized (mPackages) {
8968                        mSettings.enableSystemPackageLPw(ps.name);
8969                    }
8970                    updatedPkgBetter = true;
8971                }
8972            }
8973        }
8974
8975        if (updatedPkg != null) {
8976            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8977            // initially
8978            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8979
8980            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8981            // flag set initially
8982            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8983                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8984            }
8985        }
8986
8987        // Verify certificates against what was last scanned
8988        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8989
8990        /*
8991         * A new system app appeared, but we already had a non-system one of the
8992         * same name installed earlier.
8993         */
8994        boolean shouldHideSystemApp = false;
8995        if (updatedPkg == null && ps != null
8996                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8997            /*
8998             * Check to make sure the signatures match first. If they don't,
8999             * wipe the installed application and its data.
9000             */
9001            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9002                    != PackageManager.SIGNATURE_MATCH) {
9003                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9004                        + " signatures don't match existing userdata copy; removing");
9005                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9006                        "scanPackageInternalLI")) {
9007                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9008                }
9009                ps = null;
9010            } else {
9011                /*
9012                 * If the newly-added system app is an older version than the
9013                 * already installed version, hide it. It will be scanned later
9014                 * and re-added like an update.
9015                 */
9016                if (pkg.mVersionCode <= ps.versionCode) {
9017                    shouldHideSystemApp = true;
9018                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9019                            + " but new version " + pkg.mVersionCode + " better than installed "
9020                            + ps.versionCode + "; hiding system");
9021                } else {
9022                    /*
9023                     * The newly found system app is a newer version that the
9024                     * one previously installed. Simply remove the
9025                     * already-installed application and replace it with our own
9026                     * while keeping the application data.
9027                     */
9028                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9029                            + " reverting from " + ps.codePathString + ": new version "
9030                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9031                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9032                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9033                    synchronized (mInstallLock) {
9034                        args.cleanUpResourcesLI();
9035                    }
9036                }
9037            }
9038        }
9039
9040        // The apk is forward locked (not public) if its code and resources
9041        // are kept in different files. (except for app in either system or
9042        // vendor path).
9043        // TODO grab this value from PackageSettings
9044        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9045            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9046                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9047            }
9048        }
9049
9050        // TODO: extend to support forward-locked splits
9051        String resourcePath = null;
9052        String baseResourcePath = null;
9053        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9054            if (ps != null && ps.resourcePathString != null) {
9055                resourcePath = ps.resourcePathString;
9056                baseResourcePath = ps.resourcePathString;
9057            } else {
9058                // Should not happen at all. Just log an error.
9059                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9060            }
9061        } else {
9062            resourcePath = pkg.codePath;
9063            baseResourcePath = pkg.baseCodePath;
9064        }
9065
9066        // Set application objects path explicitly.
9067        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9068        pkg.setApplicationInfoCodePath(pkg.codePath);
9069        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9070        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9071        pkg.setApplicationInfoResourcePath(resourcePath);
9072        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9073        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9074
9075        final int userId = ((user == null) ? 0 : user.getIdentifier());
9076        if (ps != null && ps.getInstantApp(userId)) {
9077            scanFlags |= SCAN_AS_INSTANT_APP;
9078        }
9079
9080        // Note that we invoke the following method only if we are about to unpack an application
9081        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9082                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9083
9084        /*
9085         * If the system app should be overridden by a previously installed
9086         * data, hide the system app now and let the /data/app scan pick it up
9087         * again.
9088         */
9089        if (shouldHideSystemApp) {
9090            synchronized (mPackages) {
9091                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9092            }
9093        }
9094
9095        return scannedPkg;
9096    }
9097
9098    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9099        // Derive the new package synthetic package name
9100        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9101                + pkg.staticSharedLibVersion);
9102    }
9103
9104    private static String fixProcessName(String defProcessName,
9105            String processName) {
9106        if (processName == null) {
9107            return defProcessName;
9108        }
9109        return processName;
9110    }
9111
9112    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9113            throws PackageManagerException {
9114        if (pkgSetting.signatures.mSignatures != null) {
9115            // Already existing package. Make sure signatures match
9116            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9117                    == PackageManager.SIGNATURE_MATCH;
9118            if (!match) {
9119                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9120                        == PackageManager.SIGNATURE_MATCH;
9121            }
9122            if (!match) {
9123                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9124                        == PackageManager.SIGNATURE_MATCH;
9125            }
9126            if (!match) {
9127                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9128                        + pkg.packageName + " signatures do not match the "
9129                        + "previously installed version; ignoring!");
9130            }
9131        }
9132
9133        // Check for shared user signatures
9134        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9135            // Already existing package. Make sure signatures match
9136            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9137                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9138            if (!match) {
9139                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9140                        == PackageManager.SIGNATURE_MATCH;
9141            }
9142            if (!match) {
9143                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9144                        == PackageManager.SIGNATURE_MATCH;
9145            }
9146            if (!match) {
9147                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9148                        "Package " + pkg.packageName
9149                        + " has no signatures that match those in shared user "
9150                        + pkgSetting.sharedUser.name + "; ignoring!");
9151            }
9152        }
9153    }
9154
9155    /**
9156     * Enforces that only the system UID or root's UID can call a method exposed
9157     * via Binder.
9158     *
9159     * @param message used as message if SecurityException is thrown
9160     * @throws SecurityException if the caller is not system or root
9161     */
9162    private static final void enforceSystemOrRoot(String message) {
9163        final int uid = Binder.getCallingUid();
9164        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9165            throw new SecurityException(message);
9166        }
9167    }
9168
9169    @Override
9170    public void performFstrimIfNeeded() {
9171        enforceSystemOrRoot("Only the system can request fstrim");
9172
9173        // Before everything else, see whether we need to fstrim.
9174        try {
9175            IStorageManager sm = PackageHelper.getStorageManager();
9176            if (sm != null) {
9177                boolean doTrim = false;
9178                final long interval = android.provider.Settings.Global.getLong(
9179                        mContext.getContentResolver(),
9180                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9181                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9182                if (interval > 0) {
9183                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9184                    if (timeSinceLast > interval) {
9185                        doTrim = true;
9186                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9187                                + "; running immediately");
9188                    }
9189                }
9190                if (doTrim) {
9191                    final boolean dexOptDialogShown;
9192                    synchronized (mPackages) {
9193                        dexOptDialogShown = mDexOptDialogShown;
9194                    }
9195                    if (!isFirstBoot() && dexOptDialogShown) {
9196                        try {
9197                            ActivityManager.getService().showBootMessage(
9198                                    mContext.getResources().getString(
9199                                            R.string.android_upgrading_fstrim), true);
9200                        } catch (RemoteException e) {
9201                        }
9202                    }
9203                    sm.runMaintenance();
9204                }
9205            } else {
9206                Slog.e(TAG, "storageManager service unavailable!");
9207            }
9208        } catch (RemoteException e) {
9209            // Can't happen; StorageManagerService is local
9210        }
9211    }
9212
9213    @Override
9214    public void updatePackagesIfNeeded() {
9215        enforceSystemOrRoot("Only the system can request package update");
9216
9217        // We need to re-extract after an OTA.
9218        boolean causeUpgrade = isUpgrade();
9219
9220        // First boot or factory reset.
9221        // Note: we also handle devices that are upgrading to N right now as if it is their
9222        //       first boot, as they do not have profile data.
9223        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9224
9225        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9226        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9227
9228        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9229            return;
9230        }
9231
9232        List<PackageParser.Package> pkgs;
9233        synchronized (mPackages) {
9234            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9235        }
9236
9237        final long startTime = System.nanoTime();
9238        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9239                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9240
9241        final int elapsedTimeSeconds =
9242                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9243
9244        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9245        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9246        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9247        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9248        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9249    }
9250
9251    /**
9252     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9253     * containing statistics about the invocation. The array consists of three elements,
9254     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9255     * and {@code numberOfPackagesFailed}.
9256     */
9257    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9258            String compilerFilter) {
9259
9260        int numberOfPackagesVisited = 0;
9261        int numberOfPackagesOptimized = 0;
9262        int numberOfPackagesSkipped = 0;
9263        int numberOfPackagesFailed = 0;
9264        final int numberOfPackagesToDexopt = pkgs.size();
9265
9266        for (PackageParser.Package pkg : pkgs) {
9267            numberOfPackagesVisited++;
9268
9269            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9270                if (DEBUG_DEXOPT) {
9271                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9272                }
9273                numberOfPackagesSkipped++;
9274                continue;
9275            }
9276
9277            if (DEBUG_DEXOPT) {
9278                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9279                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9280            }
9281
9282            if (showDialog) {
9283                try {
9284                    ActivityManager.getService().showBootMessage(
9285                            mContext.getResources().getString(R.string.android_upgrading_apk,
9286                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9287                } catch (RemoteException e) {
9288                }
9289                synchronized (mPackages) {
9290                    mDexOptDialogShown = true;
9291                }
9292            }
9293
9294            // If the OTA updates a system app which was previously preopted to a non-preopted state
9295            // the app might end up being verified at runtime. That's because by default the apps
9296            // are verify-profile but for preopted apps there's no profile.
9297            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9298            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9299            // filter (by default 'quicken').
9300            // Note that at this stage unused apps are already filtered.
9301            if (isSystemApp(pkg) &&
9302                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9303                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9304                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9305            }
9306
9307            // checkProfiles is false to avoid merging profiles during boot which
9308            // might interfere with background compilation (b/28612421).
9309            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9310            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9311            // trade-off worth doing to save boot time work.
9312            int dexOptStatus = performDexOptTraced(pkg.packageName,
9313                    false /* checkProfiles */,
9314                    compilerFilter,
9315                    false /* force */);
9316            switch (dexOptStatus) {
9317                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9318                    numberOfPackagesOptimized++;
9319                    break;
9320                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9321                    numberOfPackagesSkipped++;
9322                    break;
9323                case PackageDexOptimizer.DEX_OPT_FAILED:
9324                    numberOfPackagesFailed++;
9325                    break;
9326                default:
9327                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9328                    break;
9329            }
9330        }
9331
9332        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9333                numberOfPackagesFailed };
9334    }
9335
9336    @Override
9337    public void notifyPackageUse(String packageName, int reason) {
9338        synchronized (mPackages) {
9339            final int callingUid = Binder.getCallingUid();
9340            final int callingUserId = UserHandle.getUserId(callingUid);
9341            if (getInstantAppPackageName(callingUid) != null) {
9342                if (!isCallerSameApp(packageName, callingUid)) {
9343                    return;
9344                }
9345            } else {
9346                if (isInstantApp(packageName, callingUserId)) {
9347                    return;
9348                }
9349            }
9350            final PackageParser.Package p = mPackages.get(packageName);
9351            if (p == null) {
9352                return;
9353            }
9354            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9355        }
9356    }
9357
9358    @Override
9359    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9360        int userId = UserHandle.getCallingUserId();
9361        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9362        if (ai == null) {
9363            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9364                + loadingPackageName + ", user=" + userId);
9365            return;
9366        }
9367        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9368    }
9369
9370    @Override
9371    public boolean performDexOpt(String packageName,
9372            boolean checkProfiles, int compileReason, boolean force) {
9373        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9374            return false;
9375        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9376            return false;
9377        }
9378        return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9379                PackageDexOptimizer.DEX_OPT_FAILED;
9380    }
9381
9382    /**
9383     * Perform dexopt on the given package and return one of following result:
9384     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9385     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9386     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9387     */
9388    /* package */ int performDexOptWithStatus(String packageName,
9389            boolean checkProfiles, int compileReason, boolean force) {
9390        return performDexOptTraced(packageName, checkProfiles,
9391                getCompilerFilterForReason(compileReason), force);
9392    }
9393
9394    @Override
9395    public boolean performDexOptMode(String packageName,
9396            boolean checkProfiles, String targetCompilerFilter, boolean force) {
9397        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9398            return false;
9399        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9400            return false;
9401        }
9402        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9403                targetCompilerFilter, force);
9404        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9405    }
9406
9407    private int performDexOptTraced(String packageName,
9408                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9409        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9410        try {
9411            return performDexOptInternal(packageName, checkProfiles,
9412                    targetCompilerFilter, force);
9413        } finally {
9414            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9415        }
9416    }
9417
9418    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9419    // if the package can now be considered up to date for the given filter.
9420    private int performDexOptInternal(String packageName,
9421                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9422        PackageParser.Package p;
9423        synchronized (mPackages) {
9424            p = mPackages.get(packageName);
9425            if (p == null) {
9426                // Package could not be found. Report failure.
9427                return PackageDexOptimizer.DEX_OPT_FAILED;
9428            }
9429            mPackageUsage.maybeWriteAsync(mPackages);
9430            mCompilerStats.maybeWriteAsync();
9431        }
9432        long callingId = Binder.clearCallingIdentity();
9433        try {
9434            synchronized (mInstallLock) {
9435                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9436                        targetCompilerFilter, force);
9437            }
9438        } finally {
9439            Binder.restoreCallingIdentity(callingId);
9440        }
9441    }
9442
9443    public ArraySet<String> getOptimizablePackages() {
9444        ArraySet<String> pkgs = new ArraySet<String>();
9445        synchronized (mPackages) {
9446            for (PackageParser.Package p : mPackages.values()) {
9447                if (PackageDexOptimizer.canOptimizePackage(p)) {
9448                    pkgs.add(p.packageName);
9449                }
9450            }
9451        }
9452        return pkgs;
9453    }
9454
9455    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9456            boolean checkProfiles, String targetCompilerFilter,
9457            boolean force) {
9458        // Select the dex optimizer based on the force parameter.
9459        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9460        //       allocate an object here.
9461        PackageDexOptimizer pdo = force
9462                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9463                : mPackageDexOptimizer;
9464
9465        // Dexopt all dependencies first. Note: we ignore the return value and march on
9466        // on errors.
9467        // Note that we are going to call performDexOpt on those libraries as many times as
9468        // they are referenced in packages. When we do a batch of performDexOpt (for example
9469        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9470        // and the first package that uses the library will dexopt it. The
9471        // others will see that the compiled code for the library is up to date.
9472        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9473        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9474        if (!deps.isEmpty()) {
9475            for (PackageParser.Package depPackage : deps) {
9476                // TODO: Analyze and investigate if we (should) profile libraries.
9477                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9478                        false /* checkProfiles */,
9479                        targetCompilerFilter,
9480                        getOrCreateCompilerPackageStats(depPackage),
9481                        true /* isUsedByOtherApps */);
9482            }
9483        }
9484        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9485                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9486                mDexManager.isUsedByOtherApps(p.packageName));
9487    }
9488
9489    // Performs dexopt on the used secondary dex files belonging to the given package.
9490    // Returns true if all dex files were process successfully (which could mean either dexopt or
9491    // skip). Returns false if any of the files caused errors.
9492    @Override
9493    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9494            boolean force) {
9495        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9496            return false;
9497        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9498            return false;
9499        }
9500        mDexManager.reconcileSecondaryDexFiles(packageName);
9501        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9502    }
9503
9504    public boolean performDexOptSecondary(String packageName, int compileReason,
9505            boolean force) {
9506        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9507    }
9508
9509    /**
9510     * Reconcile the information we have about the secondary dex files belonging to
9511     * {@code packagName} and the actual dex files. For all dex files that were
9512     * deleted, update the internal records and delete the generated oat files.
9513     */
9514    @Override
9515    public void reconcileSecondaryDexFiles(String packageName) {
9516        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9517            return;
9518        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9519            return;
9520        }
9521        mDexManager.reconcileSecondaryDexFiles(packageName);
9522    }
9523
9524    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9525    // a reference there.
9526    /*package*/ DexManager getDexManager() {
9527        return mDexManager;
9528    }
9529
9530    /**
9531     * Execute the background dexopt job immediately.
9532     */
9533    @Override
9534    public boolean runBackgroundDexoptJob() {
9535        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9536            return false;
9537        }
9538        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9539    }
9540
9541    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9542        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9543                || p.usesStaticLibraries != null) {
9544            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9545            Set<String> collectedNames = new HashSet<>();
9546            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9547
9548            retValue.remove(p);
9549
9550            return retValue;
9551        } else {
9552            return Collections.emptyList();
9553        }
9554    }
9555
9556    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9557            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9558        if (!collectedNames.contains(p.packageName)) {
9559            collectedNames.add(p.packageName);
9560            collected.add(p);
9561
9562            if (p.usesLibraries != null) {
9563                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9564                        null, collected, collectedNames);
9565            }
9566            if (p.usesOptionalLibraries != null) {
9567                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9568                        null, collected, collectedNames);
9569            }
9570            if (p.usesStaticLibraries != null) {
9571                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9572                        p.usesStaticLibrariesVersions, collected, collectedNames);
9573            }
9574        }
9575    }
9576
9577    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9578            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9579        final int libNameCount = libs.size();
9580        for (int i = 0; i < libNameCount; i++) {
9581            String libName = libs.get(i);
9582            int version = (versions != null && versions.length == libNameCount)
9583                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9584            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9585            if (libPkg != null) {
9586                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9587            }
9588        }
9589    }
9590
9591    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9592        synchronized (mPackages) {
9593            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9594            if (libEntry != null) {
9595                return mPackages.get(libEntry.apk);
9596            }
9597            return null;
9598        }
9599    }
9600
9601    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9602        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9603        if (versionedLib == null) {
9604            return null;
9605        }
9606        return versionedLib.get(version);
9607    }
9608
9609    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9610        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9611                pkg.staticSharedLibName);
9612        if (versionedLib == null) {
9613            return null;
9614        }
9615        int previousLibVersion = -1;
9616        final int versionCount = versionedLib.size();
9617        for (int i = 0; i < versionCount; i++) {
9618            final int libVersion = versionedLib.keyAt(i);
9619            if (libVersion < pkg.staticSharedLibVersion) {
9620                previousLibVersion = Math.max(previousLibVersion, libVersion);
9621            }
9622        }
9623        if (previousLibVersion >= 0) {
9624            return versionedLib.get(previousLibVersion);
9625        }
9626        return null;
9627    }
9628
9629    public void shutdown() {
9630        mPackageUsage.writeNow(mPackages);
9631        mCompilerStats.writeNow();
9632    }
9633
9634    @Override
9635    public void dumpProfiles(String packageName) {
9636        PackageParser.Package pkg;
9637        synchronized (mPackages) {
9638            pkg = mPackages.get(packageName);
9639            if (pkg == null) {
9640                throw new IllegalArgumentException("Unknown package: " + packageName);
9641            }
9642        }
9643        /* Only the shell, root, or the app user should be able to dump profiles. */
9644        int callingUid = Binder.getCallingUid();
9645        if (callingUid != Process.SHELL_UID &&
9646            callingUid != Process.ROOT_UID &&
9647            callingUid != pkg.applicationInfo.uid) {
9648            throw new SecurityException("dumpProfiles");
9649        }
9650
9651        synchronized (mInstallLock) {
9652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9653            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9654            try {
9655                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9656                String codePaths = TextUtils.join(";", allCodePaths);
9657                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9658            } catch (InstallerException e) {
9659                Slog.w(TAG, "Failed to dump profiles", e);
9660            }
9661            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9662        }
9663    }
9664
9665    @Override
9666    public void forceDexOpt(String packageName) {
9667        enforceSystemOrRoot("forceDexOpt");
9668
9669        PackageParser.Package pkg;
9670        synchronized (mPackages) {
9671            pkg = mPackages.get(packageName);
9672            if (pkg == null) {
9673                throw new IllegalArgumentException("Unknown package: " + packageName);
9674            }
9675        }
9676
9677        synchronized (mInstallLock) {
9678            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9679
9680            // Whoever is calling forceDexOpt wants a compiled package.
9681            // Don't use profiles since that may cause compilation to be skipped.
9682            final int res = performDexOptInternalWithDependenciesLI(pkg,
9683                    false /* checkProfiles */, getDefaultCompilerFilter(),
9684                    true /* force */);
9685
9686            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9687            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9688                throw new IllegalStateException("Failed to dexopt: " + res);
9689            }
9690        }
9691    }
9692
9693    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9694        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9695            Slog.w(TAG, "Unable to update from " + oldPkg.name
9696                    + " to " + newPkg.packageName
9697                    + ": old package not in system partition");
9698            return false;
9699        } else if (mPackages.get(oldPkg.name) != null) {
9700            Slog.w(TAG, "Unable to update from " + oldPkg.name
9701                    + " to " + newPkg.packageName
9702                    + ": old package still exists");
9703            return false;
9704        }
9705        return true;
9706    }
9707
9708    void removeCodePathLI(File codePath) {
9709        if (codePath.isDirectory()) {
9710            try {
9711                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9712            } catch (InstallerException e) {
9713                Slog.w(TAG, "Failed to remove code path", e);
9714            }
9715        } else {
9716            codePath.delete();
9717        }
9718    }
9719
9720    private int[] resolveUserIds(int userId) {
9721        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9722    }
9723
9724    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9725        if (pkg == null) {
9726            Slog.wtf(TAG, "Package was null!", new Throwable());
9727            return;
9728        }
9729        clearAppDataLeafLIF(pkg, userId, flags);
9730        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9731        for (int i = 0; i < childCount; i++) {
9732            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9733        }
9734    }
9735
9736    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9737        final PackageSetting ps;
9738        synchronized (mPackages) {
9739            ps = mSettings.mPackages.get(pkg.packageName);
9740        }
9741        for (int realUserId : resolveUserIds(userId)) {
9742            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9743            try {
9744                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9745                        ceDataInode);
9746            } catch (InstallerException e) {
9747                Slog.w(TAG, String.valueOf(e));
9748            }
9749        }
9750    }
9751
9752    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9753        if (pkg == null) {
9754            Slog.wtf(TAG, "Package was null!", new Throwable());
9755            return;
9756        }
9757        destroyAppDataLeafLIF(pkg, userId, flags);
9758        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9759        for (int i = 0; i < childCount; i++) {
9760            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9761        }
9762    }
9763
9764    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9765        final PackageSetting ps;
9766        synchronized (mPackages) {
9767            ps = mSettings.mPackages.get(pkg.packageName);
9768        }
9769        for (int realUserId : resolveUserIds(userId)) {
9770            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9771            try {
9772                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9773                        ceDataInode);
9774            } catch (InstallerException e) {
9775                Slog.w(TAG, String.valueOf(e));
9776            }
9777            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9778        }
9779    }
9780
9781    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9782        if (pkg == null) {
9783            Slog.wtf(TAG, "Package was null!", new Throwable());
9784            return;
9785        }
9786        destroyAppProfilesLeafLIF(pkg);
9787        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9788        for (int i = 0; i < childCount; i++) {
9789            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9790        }
9791    }
9792
9793    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9794        try {
9795            mInstaller.destroyAppProfiles(pkg.packageName);
9796        } catch (InstallerException e) {
9797            Slog.w(TAG, String.valueOf(e));
9798        }
9799    }
9800
9801    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9802        if (pkg == null) {
9803            Slog.wtf(TAG, "Package was null!", new Throwable());
9804            return;
9805        }
9806        clearAppProfilesLeafLIF(pkg);
9807        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9808        for (int i = 0; i < childCount; i++) {
9809            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9810        }
9811    }
9812
9813    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9814        try {
9815            mInstaller.clearAppProfiles(pkg.packageName);
9816        } catch (InstallerException e) {
9817            Slog.w(TAG, String.valueOf(e));
9818        }
9819    }
9820
9821    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9822            long lastUpdateTime) {
9823        // Set parent install/update time
9824        PackageSetting ps = (PackageSetting) pkg.mExtras;
9825        if (ps != null) {
9826            ps.firstInstallTime = firstInstallTime;
9827            ps.lastUpdateTime = lastUpdateTime;
9828        }
9829        // Set children install/update time
9830        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9831        for (int i = 0; i < childCount; i++) {
9832            PackageParser.Package childPkg = pkg.childPackages.get(i);
9833            ps = (PackageSetting) childPkg.mExtras;
9834            if (ps != null) {
9835                ps.firstInstallTime = firstInstallTime;
9836                ps.lastUpdateTime = lastUpdateTime;
9837            }
9838        }
9839    }
9840
9841    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9842            PackageParser.Package changingLib) {
9843        if (file.path != null) {
9844            usesLibraryFiles.add(file.path);
9845            return;
9846        }
9847        PackageParser.Package p = mPackages.get(file.apk);
9848        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9849            // If we are doing this while in the middle of updating a library apk,
9850            // then we need to make sure to use that new apk for determining the
9851            // dependencies here.  (We haven't yet finished committing the new apk
9852            // to the package manager state.)
9853            if (p == null || p.packageName.equals(changingLib.packageName)) {
9854                p = changingLib;
9855            }
9856        }
9857        if (p != null) {
9858            usesLibraryFiles.addAll(p.getAllCodePaths());
9859            if (p.usesLibraryFiles != null) {
9860                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9861            }
9862        }
9863    }
9864
9865    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9866            PackageParser.Package changingLib) throws PackageManagerException {
9867        if (pkg == null) {
9868            return;
9869        }
9870        ArraySet<String> usesLibraryFiles = null;
9871        if (pkg.usesLibraries != null) {
9872            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9873                    null, null, pkg.packageName, changingLib, true, null);
9874        }
9875        if (pkg.usesStaticLibraries != null) {
9876            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9877                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9878                    pkg.packageName, changingLib, true, usesLibraryFiles);
9879        }
9880        if (pkg.usesOptionalLibraries != null) {
9881            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9882                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9883        }
9884        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9885            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9886        } else {
9887            pkg.usesLibraryFiles = null;
9888        }
9889    }
9890
9891    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9892            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9893            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9894            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9895            throws PackageManagerException {
9896        final int libCount = requestedLibraries.size();
9897        for (int i = 0; i < libCount; i++) {
9898            final String libName = requestedLibraries.get(i);
9899            final int libVersion = requiredVersions != null ? requiredVersions[i]
9900                    : SharedLibraryInfo.VERSION_UNDEFINED;
9901            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9902            if (libEntry == null) {
9903                if (required) {
9904                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9905                            "Package " + packageName + " requires unavailable shared library "
9906                                    + libName + "; failing!");
9907                } else if (DEBUG_SHARED_LIBRARIES) {
9908                    Slog.i(TAG, "Package " + packageName
9909                            + " desires unavailable shared library "
9910                            + libName + "; ignoring!");
9911                }
9912            } else {
9913                if (requiredVersions != null && requiredCertDigests != null) {
9914                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9915                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9916                            "Package " + packageName + " requires unavailable static shared"
9917                                    + " library " + libName + " version "
9918                                    + libEntry.info.getVersion() + "; failing!");
9919                    }
9920
9921                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9922                    if (libPkg == null) {
9923                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9924                                "Package " + packageName + " requires unavailable static shared"
9925                                        + " library; failing!");
9926                    }
9927
9928                    String expectedCertDigest = requiredCertDigests[i];
9929                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9930                                libPkg.mSignatures[0]);
9931                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9932                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9933                                "Package " + packageName + " requires differently signed" +
9934                                        " static shared library; failing!");
9935                    }
9936                }
9937
9938                if (outUsedLibraries == null) {
9939                    outUsedLibraries = new ArraySet<>();
9940                }
9941                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9942            }
9943        }
9944        return outUsedLibraries;
9945    }
9946
9947    private static boolean hasString(List<String> list, List<String> which) {
9948        if (list == null) {
9949            return false;
9950        }
9951        for (int i=list.size()-1; i>=0; i--) {
9952            for (int j=which.size()-1; j>=0; j--) {
9953                if (which.get(j).equals(list.get(i))) {
9954                    return true;
9955                }
9956            }
9957        }
9958        return false;
9959    }
9960
9961    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9962            PackageParser.Package changingPkg) {
9963        ArrayList<PackageParser.Package> res = null;
9964        for (PackageParser.Package pkg : mPackages.values()) {
9965            if (changingPkg != null
9966                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9967                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9968                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9969                            changingPkg.staticSharedLibName)) {
9970                return null;
9971            }
9972            if (res == null) {
9973                res = new ArrayList<>();
9974            }
9975            res.add(pkg);
9976            try {
9977                updateSharedLibrariesLPr(pkg, changingPkg);
9978            } catch (PackageManagerException e) {
9979                // If a system app update or an app and a required lib missing we
9980                // delete the package and for updated system apps keep the data as
9981                // it is better for the user to reinstall than to be in an limbo
9982                // state. Also libs disappearing under an app should never happen
9983                // - just in case.
9984                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9985                    final int flags = pkg.isUpdatedSystemApp()
9986                            ? PackageManager.DELETE_KEEP_DATA : 0;
9987                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9988                            flags , null, true, null);
9989                }
9990                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9991            }
9992        }
9993        return res;
9994    }
9995
9996    /**
9997     * Derive the value of the {@code cpuAbiOverride} based on the provided
9998     * value and an optional stored value from the package settings.
9999     */
10000    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10001        String cpuAbiOverride = null;
10002
10003        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10004            cpuAbiOverride = null;
10005        } else if (abiOverride != null) {
10006            cpuAbiOverride = abiOverride;
10007        } else if (settings != null) {
10008            cpuAbiOverride = settings.cpuAbiOverrideString;
10009        }
10010
10011        return cpuAbiOverride;
10012    }
10013
10014    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10015            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10016                    throws PackageManagerException {
10017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10018        // If the package has children and this is the first dive in the function
10019        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10020        // whether all packages (parent and children) would be successfully scanned
10021        // before the actual scan since scanning mutates internal state and we want
10022        // to atomically install the package and its children.
10023        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10024            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10025                scanFlags |= SCAN_CHECK_ONLY;
10026            }
10027        } else {
10028            scanFlags &= ~SCAN_CHECK_ONLY;
10029        }
10030
10031        final PackageParser.Package scannedPkg;
10032        try {
10033            // Scan the parent
10034            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10035            // Scan the children
10036            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10037            for (int i = 0; i < childCount; i++) {
10038                PackageParser.Package childPkg = pkg.childPackages.get(i);
10039                scanPackageLI(childPkg, policyFlags,
10040                        scanFlags, currentTime, user);
10041            }
10042        } finally {
10043            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10044        }
10045
10046        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10047            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10048        }
10049
10050        return scannedPkg;
10051    }
10052
10053    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10054            int scanFlags, long currentTime, @Nullable UserHandle user)
10055                    throws PackageManagerException {
10056        boolean success = false;
10057        try {
10058            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10059                    currentTime, user);
10060            success = true;
10061            return res;
10062        } finally {
10063            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10064                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10065                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10066                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10067                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10068            }
10069        }
10070    }
10071
10072    /**
10073     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10074     */
10075    private static boolean apkHasCode(String fileName) {
10076        StrictJarFile jarFile = null;
10077        try {
10078            jarFile = new StrictJarFile(fileName,
10079                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10080            return jarFile.findEntry("classes.dex") != null;
10081        } catch (IOException ignore) {
10082        } finally {
10083            try {
10084                if (jarFile != null) {
10085                    jarFile.close();
10086                }
10087            } catch (IOException ignore) {}
10088        }
10089        return false;
10090    }
10091
10092    /**
10093     * Enforces code policy for the package. This ensures that if an APK has
10094     * declared hasCode="true" in its manifest that the APK actually contains
10095     * code.
10096     *
10097     * @throws PackageManagerException If bytecode could not be found when it should exist
10098     */
10099    private static void assertCodePolicy(PackageParser.Package pkg)
10100            throws PackageManagerException {
10101        final boolean shouldHaveCode =
10102                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10103        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10104            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10105                    "Package " + pkg.baseCodePath + " code is missing");
10106        }
10107
10108        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10109            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10110                final boolean splitShouldHaveCode =
10111                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10112                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10113                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10114                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10115                }
10116            }
10117        }
10118    }
10119
10120    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10121            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10122                    throws PackageManagerException {
10123        if (DEBUG_PACKAGE_SCANNING) {
10124            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10125                Log.d(TAG, "Scanning package " + pkg.packageName);
10126        }
10127
10128        applyPolicy(pkg, policyFlags);
10129
10130        assertPackageIsValid(pkg, policyFlags, scanFlags);
10131
10132        // Initialize package source and resource directories
10133        final File scanFile = new File(pkg.codePath);
10134        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10135        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10136
10137        SharedUserSetting suid = null;
10138        PackageSetting pkgSetting = null;
10139
10140        // Getting the package setting may have a side-effect, so if we
10141        // are only checking if scan would succeed, stash a copy of the
10142        // old setting to restore at the end.
10143        PackageSetting nonMutatedPs = null;
10144
10145        // We keep references to the derived CPU Abis from settings in oder to reuse
10146        // them in the case where we're not upgrading or booting for the first time.
10147        String primaryCpuAbiFromSettings = null;
10148        String secondaryCpuAbiFromSettings = null;
10149
10150        // writer
10151        synchronized (mPackages) {
10152            if (pkg.mSharedUserId != null) {
10153                // SIDE EFFECTS; may potentially allocate a new shared user
10154                suid = mSettings.getSharedUserLPw(
10155                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10156                if (DEBUG_PACKAGE_SCANNING) {
10157                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10158                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10159                                + "): packages=" + suid.packages);
10160                }
10161            }
10162
10163            // Check if we are renaming from an original package name.
10164            PackageSetting origPackage = null;
10165            String realName = null;
10166            if (pkg.mOriginalPackages != null) {
10167                // This package may need to be renamed to a previously
10168                // installed name.  Let's check on that...
10169                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10170                if (pkg.mOriginalPackages.contains(renamed)) {
10171                    // This package had originally been installed as the
10172                    // original name, and we have already taken care of
10173                    // transitioning to the new one.  Just update the new
10174                    // one to continue using the old name.
10175                    realName = pkg.mRealPackage;
10176                    if (!pkg.packageName.equals(renamed)) {
10177                        // Callers into this function may have already taken
10178                        // care of renaming the package; only do it here if
10179                        // it is not already done.
10180                        pkg.setPackageName(renamed);
10181                    }
10182                } else {
10183                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10184                        if ((origPackage = mSettings.getPackageLPr(
10185                                pkg.mOriginalPackages.get(i))) != null) {
10186                            // We do have the package already installed under its
10187                            // original name...  should we use it?
10188                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10189                                // New package is not compatible with original.
10190                                origPackage = null;
10191                                continue;
10192                            } else if (origPackage.sharedUser != null) {
10193                                // Make sure uid is compatible between packages.
10194                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10195                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10196                                            + " to " + pkg.packageName + ": old uid "
10197                                            + origPackage.sharedUser.name
10198                                            + " differs from " + pkg.mSharedUserId);
10199                                    origPackage = null;
10200                                    continue;
10201                                }
10202                                // TODO: Add case when shared user id is added [b/28144775]
10203                            } else {
10204                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10205                                        + pkg.packageName + " to old name " + origPackage.name);
10206                            }
10207                            break;
10208                        }
10209                    }
10210                }
10211            }
10212
10213            if (mTransferedPackages.contains(pkg.packageName)) {
10214                Slog.w(TAG, "Package " + pkg.packageName
10215                        + " was transferred to another, but its .apk remains");
10216            }
10217
10218            // See comments in nonMutatedPs declaration
10219            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10220                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10221                if (foundPs != null) {
10222                    nonMutatedPs = new PackageSetting(foundPs);
10223                }
10224            }
10225
10226            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10227                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10228                if (foundPs != null) {
10229                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10230                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10231                }
10232            }
10233
10234            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10235            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10236                PackageManagerService.reportSettingsProblem(Log.WARN,
10237                        "Package " + pkg.packageName + " shared user changed from "
10238                                + (pkgSetting.sharedUser != null
10239                                        ? pkgSetting.sharedUser.name : "<nothing>")
10240                                + " to "
10241                                + (suid != null ? suid.name : "<nothing>")
10242                                + "; replacing with new");
10243                pkgSetting = null;
10244            }
10245            final PackageSetting oldPkgSetting =
10246                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10247            final PackageSetting disabledPkgSetting =
10248                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10249
10250            String[] usesStaticLibraries = null;
10251            if (pkg.usesStaticLibraries != null) {
10252                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10253                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10254            }
10255
10256            if (pkgSetting == null) {
10257                final String parentPackageName = (pkg.parentPackage != null)
10258                        ? pkg.parentPackage.packageName : null;
10259                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10260                // REMOVE SharedUserSetting from method; update in a separate call
10261                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10262                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10263                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10264                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10265                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10266                        true /*allowInstall*/, instantApp, parentPackageName,
10267                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10268                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10269                // SIDE EFFECTS; updates system state; move elsewhere
10270                if (origPackage != null) {
10271                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10272                }
10273                mSettings.addUserToSettingLPw(pkgSetting);
10274            } else {
10275                // REMOVE SharedUserSetting from method; update in a separate call.
10276                //
10277                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10278                // secondaryCpuAbi are not known at this point so we always update them
10279                // to null here, only to reset them at a later point.
10280                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10281                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10282                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10283                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10284                        UserManagerService.getInstance(), usesStaticLibraries,
10285                        pkg.usesStaticLibrariesVersions);
10286            }
10287            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10288            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10289
10290            // SIDE EFFECTS; modifies system state; move elsewhere
10291            if (pkgSetting.origPackage != null) {
10292                // If we are first transitioning from an original package,
10293                // fix up the new package's name now.  We need to do this after
10294                // looking up the package under its new name, so getPackageLP
10295                // can take care of fiddling things correctly.
10296                pkg.setPackageName(origPackage.name);
10297
10298                // File a report about this.
10299                String msg = "New package " + pkgSetting.realName
10300                        + " renamed to replace old package " + pkgSetting.name;
10301                reportSettingsProblem(Log.WARN, msg);
10302
10303                // Make a note of it.
10304                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10305                    mTransferedPackages.add(origPackage.name);
10306                }
10307
10308                // No longer need to retain this.
10309                pkgSetting.origPackage = null;
10310            }
10311
10312            // SIDE EFFECTS; modifies system state; move elsewhere
10313            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10314                // Make a note of it.
10315                mTransferedPackages.add(pkg.packageName);
10316            }
10317
10318            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10319                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10320            }
10321
10322            if ((scanFlags & SCAN_BOOTING) == 0
10323                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10324                // Check all shared libraries and map to their actual file path.
10325                // We only do this here for apps not on a system dir, because those
10326                // are the only ones that can fail an install due to this.  We
10327                // will take care of the system apps by updating all of their
10328                // library paths after the scan is done. Also during the initial
10329                // scan don't update any libs as we do this wholesale after all
10330                // apps are scanned to avoid dependency based scanning.
10331                updateSharedLibrariesLPr(pkg, null);
10332            }
10333
10334            if (mFoundPolicyFile) {
10335                SELinuxMMAC.assignSeInfoValue(pkg);
10336            }
10337            pkg.applicationInfo.uid = pkgSetting.appId;
10338            pkg.mExtras = pkgSetting;
10339
10340
10341            // Static shared libs have same package with different versions where
10342            // we internally use a synthetic package name to allow multiple versions
10343            // of the same package, therefore we need to compare signatures against
10344            // the package setting for the latest library version.
10345            PackageSetting signatureCheckPs = pkgSetting;
10346            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10347                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10348                if (libraryEntry != null) {
10349                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10350                }
10351            }
10352
10353            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10354                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10355                    // We just determined the app is signed correctly, so bring
10356                    // over the latest parsed certs.
10357                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10358                } else {
10359                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10360                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10361                                "Package " + pkg.packageName + " upgrade keys do not match the "
10362                                + "previously installed version");
10363                    } else {
10364                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10365                        String msg = "System package " + pkg.packageName
10366                                + " signature changed; retaining data.";
10367                        reportSettingsProblem(Log.WARN, msg);
10368                    }
10369                }
10370            } else {
10371                try {
10372                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10373                    verifySignaturesLP(signatureCheckPs, pkg);
10374                    // We just determined the app is signed correctly, so bring
10375                    // over the latest parsed certs.
10376                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10377                } catch (PackageManagerException e) {
10378                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10379                        throw e;
10380                    }
10381                    // The signature has changed, but this package is in the system
10382                    // image...  let's recover!
10383                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10384                    // However...  if this package is part of a shared user, but it
10385                    // doesn't match the signature of the shared user, let's fail.
10386                    // What this means is that you can't change the signatures
10387                    // associated with an overall shared user, which doesn't seem all
10388                    // that unreasonable.
10389                    if (signatureCheckPs.sharedUser != null) {
10390                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10391                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10392                            throw new PackageManagerException(
10393                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10394                                    "Signature mismatch for shared user: "
10395                                            + pkgSetting.sharedUser);
10396                        }
10397                    }
10398                    // File a report about this.
10399                    String msg = "System package " + pkg.packageName
10400                            + " signature changed; retaining data.";
10401                    reportSettingsProblem(Log.WARN, msg);
10402                }
10403            }
10404
10405            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10406                // This package wants to adopt ownership of permissions from
10407                // another package.
10408                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10409                    final String origName = pkg.mAdoptPermissions.get(i);
10410                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10411                    if (orig != null) {
10412                        if (verifyPackageUpdateLPr(orig, pkg)) {
10413                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10414                                    + pkg.packageName);
10415                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10416                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10417                        }
10418                    }
10419                }
10420            }
10421        }
10422
10423        pkg.applicationInfo.processName = fixProcessName(
10424                pkg.applicationInfo.packageName,
10425                pkg.applicationInfo.processName);
10426
10427        if (pkg != mPlatformPackage) {
10428            // Get all of our default paths setup
10429            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10430        }
10431
10432        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10433
10434        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10435            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10436                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10437                final boolean extractNativeLibs = !pkg.isLibrary();
10438                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10439                        mAppLib32InstallDir);
10440                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10441
10442                // Some system apps still use directory structure for native libraries
10443                // in which case we might end up not detecting abi solely based on apk
10444                // structure. Try to detect abi based on directory structure.
10445                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10446                        pkg.applicationInfo.primaryCpuAbi == null) {
10447                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10448                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10449                }
10450            } else {
10451                // This is not a first boot or an upgrade, don't bother deriving the
10452                // ABI during the scan. Instead, trust the value that was stored in the
10453                // package setting.
10454                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10455                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10456
10457                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10458
10459                if (DEBUG_ABI_SELECTION) {
10460                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10461                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10462                        pkg.applicationInfo.secondaryCpuAbi);
10463                }
10464            }
10465        } else {
10466            if ((scanFlags & SCAN_MOVE) != 0) {
10467                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10468                // but we already have this packages package info in the PackageSetting. We just
10469                // use that and derive the native library path based on the new codepath.
10470                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10471                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10472            }
10473
10474            // Set native library paths again. For moves, the path will be updated based on the
10475            // ABIs we've determined above. For non-moves, the path will be updated based on the
10476            // ABIs we determined during compilation, but the path will depend on the final
10477            // package path (after the rename away from the stage path).
10478            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10479        }
10480
10481        // This is a special case for the "system" package, where the ABI is
10482        // dictated by the zygote configuration (and init.rc). We should keep track
10483        // of this ABI so that we can deal with "normal" applications that run under
10484        // the same UID correctly.
10485        if (mPlatformPackage == pkg) {
10486            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10487                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10488        }
10489
10490        // If there's a mismatch between the abi-override in the package setting
10491        // and the abiOverride specified for the install. Warn about this because we
10492        // would've already compiled the app without taking the package setting into
10493        // account.
10494        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10495            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10496                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10497                        " for package " + pkg.packageName);
10498            }
10499        }
10500
10501        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10502        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10503        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10504
10505        // Copy the derived override back to the parsed package, so that we can
10506        // update the package settings accordingly.
10507        pkg.cpuAbiOverride = cpuAbiOverride;
10508
10509        if (DEBUG_ABI_SELECTION) {
10510            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10511                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10512                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10513        }
10514
10515        // Push the derived path down into PackageSettings so we know what to
10516        // clean up at uninstall time.
10517        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10518
10519        if (DEBUG_ABI_SELECTION) {
10520            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10521                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10522                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10523        }
10524
10525        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10526        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10527            // We don't do this here during boot because we can do it all
10528            // at once after scanning all existing packages.
10529            //
10530            // We also do this *before* we perform dexopt on this package, so that
10531            // we can avoid redundant dexopts, and also to make sure we've got the
10532            // code and package path correct.
10533            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10534        }
10535
10536        if (mFactoryTest && pkg.requestedPermissions.contains(
10537                android.Manifest.permission.FACTORY_TEST)) {
10538            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10539        }
10540
10541        if (isSystemApp(pkg)) {
10542            pkgSetting.isOrphaned = true;
10543        }
10544
10545        // Take care of first install / last update times.
10546        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10547        if (currentTime != 0) {
10548            if (pkgSetting.firstInstallTime == 0) {
10549                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10550            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10551                pkgSetting.lastUpdateTime = currentTime;
10552            }
10553        } else if (pkgSetting.firstInstallTime == 0) {
10554            // We need *something*.  Take time time stamp of the file.
10555            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10556        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10557            if (scanFileTime != pkgSetting.timeStamp) {
10558                // A package on the system image has changed; consider this
10559                // to be an update.
10560                pkgSetting.lastUpdateTime = scanFileTime;
10561            }
10562        }
10563        pkgSetting.setTimeStamp(scanFileTime);
10564
10565        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10566            if (nonMutatedPs != null) {
10567                synchronized (mPackages) {
10568                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10569                }
10570            }
10571        } else {
10572            final int userId = user == null ? 0 : user.getIdentifier();
10573            // Modify state for the given package setting
10574            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10575                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10576            if (pkgSetting.getInstantApp(userId)) {
10577                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10578            }
10579        }
10580        return pkg;
10581    }
10582
10583    /**
10584     * Applies policy to the parsed package based upon the given policy flags.
10585     * Ensures the package is in a good state.
10586     * <p>
10587     * Implementation detail: This method must NOT have any side effect. It would
10588     * ideally be static, but, it requires locks to read system state.
10589     */
10590    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10591        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10592            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10593            if (pkg.applicationInfo.isDirectBootAware()) {
10594                // we're direct boot aware; set for all components
10595                for (PackageParser.Service s : pkg.services) {
10596                    s.info.encryptionAware = s.info.directBootAware = true;
10597                }
10598                for (PackageParser.Provider p : pkg.providers) {
10599                    p.info.encryptionAware = p.info.directBootAware = true;
10600                }
10601                for (PackageParser.Activity a : pkg.activities) {
10602                    a.info.encryptionAware = a.info.directBootAware = true;
10603                }
10604                for (PackageParser.Activity r : pkg.receivers) {
10605                    r.info.encryptionAware = r.info.directBootAware = true;
10606                }
10607            }
10608        } else {
10609            // Only allow system apps to be flagged as core apps.
10610            pkg.coreApp = false;
10611            // clear flags not applicable to regular apps
10612            pkg.applicationInfo.privateFlags &=
10613                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10614            pkg.applicationInfo.privateFlags &=
10615                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10616        }
10617        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10618
10619        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10620            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10621        }
10622
10623        if (!isSystemApp(pkg)) {
10624            // Only system apps can use these features.
10625            pkg.mOriginalPackages = null;
10626            pkg.mRealPackage = null;
10627            pkg.mAdoptPermissions = null;
10628        }
10629    }
10630
10631    /**
10632     * Asserts the parsed package is valid according to the given policy. If the
10633     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10634     * <p>
10635     * Implementation detail: This method must NOT have any side effects. It would
10636     * ideally be static, but, it requires locks to read system state.
10637     *
10638     * @throws PackageManagerException If the package fails any of the validation checks
10639     */
10640    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10641            throws PackageManagerException {
10642        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10643            assertCodePolicy(pkg);
10644        }
10645
10646        if (pkg.applicationInfo.getCodePath() == null ||
10647                pkg.applicationInfo.getResourcePath() == null) {
10648            // Bail out. The resource and code paths haven't been set.
10649            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10650                    "Code and resource paths haven't been set correctly");
10651        }
10652
10653        // Make sure we're not adding any bogus keyset info
10654        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10655        ksms.assertScannedPackageValid(pkg);
10656
10657        synchronized (mPackages) {
10658            // The special "android" package can only be defined once
10659            if (pkg.packageName.equals("android")) {
10660                if (mAndroidApplication != null) {
10661                    Slog.w(TAG, "*************************************************");
10662                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10663                    Slog.w(TAG, " codePath=" + pkg.codePath);
10664                    Slog.w(TAG, "*************************************************");
10665                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10666                            "Core android package being redefined.  Skipping.");
10667                }
10668            }
10669
10670            // A package name must be unique; don't allow duplicates
10671            if (mPackages.containsKey(pkg.packageName)) {
10672                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10673                        "Application package " + pkg.packageName
10674                        + " already installed.  Skipping duplicate.");
10675            }
10676
10677            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10678                // Static libs have a synthetic package name containing the version
10679                // but we still want the base name to be unique.
10680                if (mPackages.containsKey(pkg.manifestPackageName)) {
10681                    throw new PackageManagerException(
10682                            "Duplicate static shared lib provider package");
10683                }
10684
10685                // Static shared libraries should have at least O target SDK
10686                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10687                    throw new PackageManagerException(
10688                            "Packages declaring static-shared libs must target O SDK or higher");
10689                }
10690
10691                // Package declaring static a shared lib cannot be instant apps
10692                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10693                    throw new PackageManagerException(
10694                            "Packages declaring static-shared libs cannot be instant apps");
10695                }
10696
10697                // Package declaring static a shared lib cannot be renamed since the package
10698                // name is synthetic and apps can't code around package manager internals.
10699                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10700                    throw new PackageManagerException(
10701                            "Packages declaring static-shared libs cannot be renamed");
10702                }
10703
10704                // Package declaring static a shared lib cannot declare child packages
10705                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10706                    throw new PackageManagerException(
10707                            "Packages declaring static-shared libs cannot have child packages");
10708                }
10709
10710                // Package declaring static a shared lib cannot declare dynamic libs
10711                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10712                    throw new PackageManagerException(
10713                            "Packages declaring static-shared libs cannot declare dynamic libs");
10714                }
10715
10716                // Package declaring static a shared lib cannot declare shared users
10717                if (pkg.mSharedUserId != null) {
10718                    throw new PackageManagerException(
10719                            "Packages declaring static-shared libs cannot declare shared users");
10720                }
10721
10722                // Static shared libs cannot declare activities
10723                if (!pkg.activities.isEmpty()) {
10724                    throw new PackageManagerException(
10725                            "Static shared libs cannot declare activities");
10726                }
10727
10728                // Static shared libs cannot declare services
10729                if (!pkg.services.isEmpty()) {
10730                    throw new PackageManagerException(
10731                            "Static shared libs cannot declare services");
10732                }
10733
10734                // Static shared libs cannot declare providers
10735                if (!pkg.providers.isEmpty()) {
10736                    throw new PackageManagerException(
10737                            "Static shared libs cannot declare content providers");
10738                }
10739
10740                // Static shared libs cannot declare receivers
10741                if (!pkg.receivers.isEmpty()) {
10742                    throw new PackageManagerException(
10743                            "Static shared libs cannot declare broadcast receivers");
10744                }
10745
10746                // Static shared libs cannot declare permission groups
10747                if (!pkg.permissionGroups.isEmpty()) {
10748                    throw new PackageManagerException(
10749                            "Static shared libs cannot declare permission groups");
10750                }
10751
10752                // Static shared libs cannot declare permissions
10753                if (!pkg.permissions.isEmpty()) {
10754                    throw new PackageManagerException(
10755                            "Static shared libs cannot declare permissions");
10756                }
10757
10758                // Static shared libs cannot declare protected broadcasts
10759                if (pkg.protectedBroadcasts != null) {
10760                    throw new PackageManagerException(
10761                            "Static shared libs cannot declare protected broadcasts");
10762                }
10763
10764                // Static shared libs cannot be overlay targets
10765                if (pkg.mOverlayTarget != null) {
10766                    throw new PackageManagerException(
10767                            "Static shared libs cannot be overlay targets");
10768                }
10769
10770                // The version codes must be ordered as lib versions
10771                int minVersionCode = Integer.MIN_VALUE;
10772                int maxVersionCode = Integer.MAX_VALUE;
10773
10774                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10775                        pkg.staticSharedLibName);
10776                if (versionedLib != null) {
10777                    final int versionCount = versionedLib.size();
10778                    for (int i = 0; i < versionCount; i++) {
10779                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10780                        final int libVersionCode = libInfo.getDeclaringPackage()
10781                                .getVersionCode();
10782                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10783                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10784                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10785                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10786                        } else {
10787                            minVersionCode = maxVersionCode = libVersionCode;
10788                            break;
10789                        }
10790                    }
10791                }
10792                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10793                    throw new PackageManagerException("Static shared"
10794                            + " lib version codes must be ordered as lib versions");
10795                }
10796            }
10797
10798            // Only privileged apps and updated privileged apps can add child packages.
10799            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10800                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10801                    throw new PackageManagerException("Only privileged apps can add child "
10802                            + "packages. Ignoring package " + pkg.packageName);
10803                }
10804                final int childCount = pkg.childPackages.size();
10805                for (int i = 0; i < childCount; i++) {
10806                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10807                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10808                            childPkg.packageName)) {
10809                        throw new PackageManagerException("Can't override child of "
10810                                + "another disabled app. Ignoring package " + pkg.packageName);
10811                    }
10812                }
10813            }
10814
10815            // If we're only installing presumed-existing packages, require that the
10816            // scanned APK is both already known and at the path previously established
10817            // for it.  Previously unknown packages we pick up normally, but if we have an
10818            // a priori expectation about this package's install presence, enforce it.
10819            // With a singular exception for new system packages. When an OTA contains
10820            // a new system package, we allow the codepath to change from a system location
10821            // to the user-installed location. If we don't allow this change, any newer,
10822            // user-installed version of the application will be ignored.
10823            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10824                if (mExpectingBetter.containsKey(pkg.packageName)) {
10825                    logCriticalInfo(Log.WARN,
10826                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10827                } else {
10828                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10829                    if (known != null) {
10830                        if (DEBUG_PACKAGE_SCANNING) {
10831                            Log.d(TAG, "Examining " + pkg.codePath
10832                                    + " and requiring known paths " + known.codePathString
10833                                    + " & " + known.resourcePathString);
10834                        }
10835                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10836                                || !pkg.applicationInfo.getResourcePath().equals(
10837                                        known.resourcePathString)) {
10838                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10839                                    "Application package " + pkg.packageName
10840                                    + " found at " + pkg.applicationInfo.getCodePath()
10841                                    + " but expected at " + known.codePathString
10842                                    + "; ignoring.");
10843                        }
10844                    }
10845                }
10846            }
10847
10848            // Verify that this new package doesn't have any content providers
10849            // that conflict with existing packages.  Only do this if the
10850            // package isn't already installed, since we don't want to break
10851            // things that are installed.
10852            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10853                final int N = pkg.providers.size();
10854                int i;
10855                for (i=0; i<N; i++) {
10856                    PackageParser.Provider p = pkg.providers.get(i);
10857                    if (p.info.authority != null) {
10858                        String names[] = p.info.authority.split(";");
10859                        for (int j = 0; j < names.length; j++) {
10860                            if (mProvidersByAuthority.containsKey(names[j])) {
10861                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10862                                final String otherPackageName =
10863                                        ((other != null && other.getComponentName() != null) ?
10864                                                other.getComponentName().getPackageName() : "?");
10865                                throw new PackageManagerException(
10866                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10867                                        "Can't install because provider name " + names[j]
10868                                                + " (in package " + pkg.applicationInfo.packageName
10869                                                + ") is already used by " + otherPackageName);
10870                            }
10871                        }
10872                    }
10873                }
10874            }
10875        }
10876    }
10877
10878    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10879            int type, String declaringPackageName, int declaringVersionCode) {
10880        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10881        if (versionedLib == null) {
10882            versionedLib = new SparseArray<>();
10883            mSharedLibraries.put(name, versionedLib);
10884            if (type == SharedLibraryInfo.TYPE_STATIC) {
10885                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10886            }
10887        } else if (versionedLib.indexOfKey(version) >= 0) {
10888            return false;
10889        }
10890        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10891                version, type, declaringPackageName, declaringVersionCode);
10892        versionedLib.put(version, libEntry);
10893        return true;
10894    }
10895
10896    private boolean removeSharedLibraryLPw(String name, int version) {
10897        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10898        if (versionedLib == null) {
10899            return false;
10900        }
10901        final int libIdx = versionedLib.indexOfKey(version);
10902        if (libIdx < 0) {
10903            return false;
10904        }
10905        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10906        versionedLib.remove(version);
10907        if (versionedLib.size() <= 0) {
10908            mSharedLibraries.remove(name);
10909            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10910                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10911                        .getPackageName());
10912            }
10913        }
10914        return true;
10915    }
10916
10917    /**
10918     * Adds a scanned package to the system. When this method is finished, the package will
10919     * be available for query, resolution, etc...
10920     */
10921    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10922            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10923        final String pkgName = pkg.packageName;
10924        if (mCustomResolverComponentName != null &&
10925                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10926            setUpCustomResolverActivity(pkg);
10927        }
10928
10929        if (pkg.packageName.equals("android")) {
10930            synchronized (mPackages) {
10931                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10932                    // Set up information for our fall-back user intent resolution activity.
10933                    mPlatformPackage = pkg;
10934                    pkg.mVersionCode = mSdkVersion;
10935                    mAndroidApplication = pkg.applicationInfo;
10936                    if (!mResolverReplaced) {
10937                        mResolveActivity.applicationInfo = mAndroidApplication;
10938                        mResolveActivity.name = ResolverActivity.class.getName();
10939                        mResolveActivity.packageName = mAndroidApplication.packageName;
10940                        mResolveActivity.processName = "system:ui";
10941                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10942                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10943                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10944                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10945                        mResolveActivity.exported = true;
10946                        mResolveActivity.enabled = true;
10947                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10948                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10949                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10950                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10951                                | ActivityInfo.CONFIG_ORIENTATION
10952                                | ActivityInfo.CONFIG_KEYBOARD
10953                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10954                        mResolveInfo.activityInfo = mResolveActivity;
10955                        mResolveInfo.priority = 0;
10956                        mResolveInfo.preferredOrder = 0;
10957                        mResolveInfo.match = 0;
10958                        mResolveComponentName = new ComponentName(
10959                                mAndroidApplication.packageName, mResolveActivity.name);
10960                    }
10961                }
10962            }
10963        }
10964
10965        ArrayList<PackageParser.Package> clientLibPkgs = null;
10966        // writer
10967        synchronized (mPackages) {
10968            boolean hasStaticSharedLibs = false;
10969
10970            // Any app can add new static shared libraries
10971            if (pkg.staticSharedLibName != null) {
10972                // Static shared libs don't allow renaming as they have synthetic package
10973                // names to allow install of multiple versions, so use name from manifest.
10974                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10975                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10976                        pkg.manifestPackageName, pkg.mVersionCode)) {
10977                    hasStaticSharedLibs = true;
10978                } else {
10979                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10980                                + pkg.staticSharedLibName + " already exists; skipping");
10981                }
10982                // Static shared libs cannot be updated once installed since they
10983                // use synthetic package name which includes the version code, so
10984                // not need to update other packages's shared lib dependencies.
10985            }
10986
10987            if (!hasStaticSharedLibs
10988                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10989                // Only system apps can add new dynamic shared libraries.
10990                if (pkg.libraryNames != null) {
10991                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10992                        String name = pkg.libraryNames.get(i);
10993                        boolean allowed = false;
10994                        if (pkg.isUpdatedSystemApp()) {
10995                            // New library entries can only be added through the
10996                            // system image.  This is important to get rid of a lot
10997                            // of nasty edge cases: for example if we allowed a non-
10998                            // system update of the app to add a library, then uninstalling
10999                            // the update would make the library go away, and assumptions
11000                            // we made such as through app install filtering would now
11001                            // have allowed apps on the device which aren't compatible
11002                            // with it.  Better to just have the restriction here, be
11003                            // conservative, and create many fewer cases that can negatively
11004                            // impact the user experience.
11005                            final PackageSetting sysPs = mSettings
11006                                    .getDisabledSystemPkgLPr(pkg.packageName);
11007                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11008                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11009                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11010                                        allowed = true;
11011                                        break;
11012                                    }
11013                                }
11014                            }
11015                        } else {
11016                            allowed = true;
11017                        }
11018                        if (allowed) {
11019                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11020                                    SharedLibraryInfo.VERSION_UNDEFINED,
11021                                    SharedLibraryInfo.TYPE_DYNAMIC,
11022                                    pkg.packageName, pkg.mVersionCode)) {
11023                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11024                                        + name + " already exists; skipping");
11025                            }
11026                        } else {
11027                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11028                                    + name + " that is not declared on system image; skipping");
11029                        }
11030                    }
11031
11032                    if ((scanFlags & SCAN_BOOTING) == 0) {
11033                        // If we are not booting, we need to update any applications
11034                        // that are clients of our shared library.  If we are booting,
11035                        // this will all be done once the scan is complete.
11036                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11037                    }
11038                }
11039            }
11040        }
11041
11042        if ((scanFlags & SCAN_BOOTING) != 0) {
11043            // No apps can run during boot scan, so they don't need to be frozen
11044        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11045            // Caller asked to not kill app, so it's probably not frozen
11046        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11047            // Caller asked us to ignore frozen check for some reason; they
11048            // probably didn't know the package name
11049        } else {
11050            // We're doing major surgery on this package, so it better be frozen
11051            // right now to keep it from launching
11052            checkPackageFrozen(pkgName);
11053        }
11054
11055        // Also need to kill any apps that are dependent on the library.
11056        if (clientLibPkgs != null) {
11057            for (int i=0; i<clientLibPkgs.size(); i++) {
11058                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11059                killApplication(clientPkg.applicationInfo.packageName,
11060                        clientPkg.applicationInfo.uid, "update lib");
11061            }
11062        }
11063
11064        // writer
11065        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11066
11067        synchronized (mPackages) {
11068            // We don't expect installation to fail beyond this point
11069
11070            // Add the new setting to mSettings
11071            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11072            // Add the new setting to mPackages
11073            mPackages.put(pkg.applicationInfo.packageName, pkg);
11074            // Make sure we don't accidentally delete its data.
11075            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11076            while (iter.hasNext()) {
11077                PackageCleanItem item = iter.next();
11078                if (pkgName.equals(item.packageName)) {
11079                    iter.remove();
11080                }
11081            }
11082
11083            // Add the package's KeySets to the global KeySetManagerService
11084            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11085            ksms.addScannedPackageLPw(pkg);
11086
11087            int N = pkg.providers.size();
11088            StringBuilder r = null;
11089            int i;
11090            for (i=0; i<N; i++) {
11091                PackageParser.Provider p = pkg.providers.get(i);
11092                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11093                        p.info.processName);
11094                mProviders.addProvider(p);
11095                p.syncable = p.info.isSyncable;
11096                if (p.info.authority != null) {
11097                    String names[] = p.info.authority.split(";");
11098                    p.info.authority = null;
11099                    for (int j = 0; j < names.length; j++) {
11100                        if (j == 1 && p.syncable) {
11101                            // We only want the first authority for a provider to possibly be
11102                            // syncable, so if we already added this provider using a different
11103                            // authority clear the syncable flag. We copy the provider before
11104                            // changing it because the mProviders object contains a reference
11105                            // to a provider that we don't want to change.
11106                            // Only do this for the second authority since the resulting provider
11107                            // object can be the same for all future authorities for this provider.
11108                            p = new PackageParser.Provider(p);
11109                            p.syncable = false;
11110                        }
11111                        if (!mProvidersByAuthority.containsKey(names[j])) {
11112                            mProvidersByAuthority.put(names[j], p);
11113                            if (p.info.authority == null) {
11114                                p.info.authority = names[j];
11115                            } else {
11116                                p.info.authority = p.info.authority + ";" + names[j];
11117                            }
11118                            if (DEBUG_PACKAGE_SCANNING) {
11119                                if (chatty)
11120                                    Log.d(TAG, "Registered content provider: " + names[j]
11121                                            + ", className = " + p.info.name + ", isSyncable = "
11122                                            + p.info.isSyncable);
11123                            }
11124                        } else {
11125                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11126                            Slog.w(TAG, "Skipping provider name " + names[j] +
11127                                    " (in package " + pkg.applicationInfo.packageName +
11128                                    "): name already used by "
11129                                    + ((other != null && other.getComponentName() != null)
11130                                            ? other.getComponentName().getPackageName() : "?"));
11131                        }
11132                    }
11133                }
11134                if (chatty) {
11135                    if (r == null) {
11136                        r = new StringBuilder(256);
11137                    } else {
11138                        r.append(' ');
11139                    }
11140                    r.append(p.info.name);
11141                }
11142            }
11143            if (r != null) {
11144                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11145            }
11146
11147            N = pkg.services.size();
11148            r = null;
11149            for (i=0; i<N; i++) {
11150                PackageParser.Service s = pkg.services.get(i);
11151                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11152                        s.info.processName);
11153                mServices.addService(s);
11154                if (chatty) {
11155                    if (r == null) {
11156                        r = new StringBuilder(256);
11157                    } else {
11158                        r.append(' ');
11159                    }
11160                    r.append(s.info.name);
11161                }
11162            }
11163            if (r != null) {
11164                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11165            }
11166
11167            N = pkg.receivers.size();
11168            r = null;
11169            for (i=0; i<N; i++) {
11170                PackageParser.Activity a = pkg.receivers.get(i);
11171                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11172                        a.info.processName);
11173                mReceivers.addActivity(a, "receiver");
11174                if (chatty) {
11175                    if (r == null) {
11176                        r = new StringBuilder(256);
11177                    } else {
11178                        r.append(' ');
11179                    }
11180                    r.append(a.info.name);
11181                }
11182            }
11183            if (r != null) {
11184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11185            }
11186
11187            N = pkg.activities.size();
11188            r = null;
11189            for (i=0; i<N; i++) {
11190                PackageParser.Activity a = pkg.activities.get(i);
11191                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11192                        a.info.processName);
11193                mActivities.addActivity(a, "activity");
11194                if (chatty) {
11195                    if (r == null) {
11196                        r = new StringBuilder(256);
11197                    } else {
11198                        r.append(' ');
11199                    }
11200                    r.append(a.info.name);
11201                }
11202            }
11203            if (r != null) {
11204                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11205            }
11206
11207            N = pkg.permissionGroups.size();
11208            r = null;
11209            for (i=0; i<N; i++) {
11210                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11211                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11212                final String curPackageName = cur == null ? null : cur.info.packageName;
11213                // Dont allow ephemeral apps to define new permission groups.
11214                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11215                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11216                            + pg.info.packageName
11217                            + " ignored: instant apps cannot define new permission groups.");
11218                    continue;
11219                }
11220                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11221                if (cur == null || isPackageUpdate) {
11222                    mPermissionGroups.put(pg.info.name, pg);
11223                    if (chatty) {
11224                        if (r == null) {
11225                            r = new StringBuilder(256);
11226                        } else {
11227                            r.append(' ');
11228                        }
11229                        if (isPackageUpdate) {
11230                            r.append("UPD:");
11231                        }
11232                        r.append(pg.info.name);
11233                    }
11234                } else {
11235                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11236                            + pg.info.packageName + " ignored: original from "
11237                            + cur.info.packageName);
11238                    if (chatty) {
11239                        if (r == null) {
11240                            r = new StringBuilder(256);
11241                        } else {
11242                            r.append(' ');
11243                        }
11244                        r.append("DUP:");
11245                        r.append(pg.info.name);
11246                    }
11247                }
11248            }
11249            if (r != null) {
11250                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11251            }
11252
11253            N = pkg.permissions.size();
11254            r = null;
11255            for (i=0; i<N; i++) {
11256                PackageParser.Permission p = pkg.permissions.get(i);
11257
11258                // Dont allow ephemeral apps to define new permissions.
11259                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11260                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11261                            + p.info.packageName
11262                            + " ignored: instant apps cannot define new permissions.");
11263                    continue;
11264                }
11265
11266                // Assume by default that we did not install this permission into the system.
11267                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11268
11269                // Now that permission groups have a special meaning, we ignore permission
11270                // groups for legacy apps to prevent unexpected behavior. In particular,
11271                // permissions for one app being granted to someone just because they happen
11272                // to be in a group defined by another app (before this had no implications).
11273                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11274                    p.group = mPermissionGroups.get(p.info.group);
11275                    // Warn for a permission in an unknown group.
11276                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11277                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11278                                + p.info.packageName + " in an unknown group " + p.info.group);
11279                    }
11280                }
11281
11282                ArrayMap<String, BasePermission> permissionMap =
11283                        p.tree ? mSettings.mPermissionTrees
11284                                : mSettings.mPermissions;
11285                BasePermission bp = permissionMap.get(p.info.name);
11286
11287                // Allow system apps to redefine non-system permissions
11288                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11289                    final boolean currentOwnerIsSystem = (bp.perm != null
11290                            && isSystemApp(bp.perm.owner));
11291                    if (isSystemApp(p.owner)) {
11292                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11293                            // It's a built-in permission and no owner, take ownership now
11294                            bp.packageSetting = pkgSetting;
11295                            bp.perm = p;
11296                            bp.uid = pkg.applicationInfo.uid;
11297                            bp.sourcePackage = p.info.packageName;
11298                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11299                        } else if (!currentOwnerIsSystem) {
11300                            String msg = "New decl " + p.owner + " of permission  "
11301                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11302                            reportSettingsProblem(Log.WARN, msg);
11303                            bp = null;
11304                        }
11305                    }
11306                }
11307
11308                if (bp == null) {
11309                    bp = new BasePermission(p.info.name, p.info.packageName,
11310                            BasePermission.TYPE_NORMAL);
11311                    permissionMap.put(p.info.name, bp);
11312                }
11313
11314                if (bp.perm == null) {
11315                    if (bp.sourcePackage == null
11316                            || bp.sourcePackage.equals(p.info.packageName)) {
11317                        BasePermission tree = findPermissionTreeLP(p.info.name);
11318                        if (tree == null
11319                                || tree.sourcePackage.equals(p.info.packageName)) {
11320                            bp.packageSetting = pkgSetting;
11321                            bp.perm = p;
11322                            bp.uid = pkg.applicationInfo.uid;
11323                            bp.sourcePackage = p.info.packageName;
11324                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11325                            if (chatty) {
11326                                if (r == null) {
11327                                    r = new StringBuilder(256);
11328                                } else {
11329                                    r.append(' ');
11330                                }
11331                                r.append(p.info.name);
11332                            }
11333                        } else {
11334                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11335                                    + p.info.packageName + " ignored: base tree "
11336                                    + tree.name + " is from package "
11337                                    + tree.sourcePackage);
11338                        }
11339                    } else {
11340                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11341                                + p.info.packageName + " ignored: original from "
11342                                + bp.sourcePackage);
11343                    }
11344                } else if (chatty) {
11345                    if (r == null) {
11346                        r = new StringBuilder(256);
11347                    } else {
11348                        r.append(' ');
11349                    }
11350                    r.append("DUP:");
11351                    r.append(p.info.name);
11352                }
11353                if (bp.perm == p) {
11354                    bp.protectionLevel = p.info.protectionLevel;
11355                }
11356            }
11357
11358            if (r != null) {
11359                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11360            }
11361
11362            N = pkg.instrumentation.size();
11363            r = null;
11364            for (i=0; i<N; i++) {
11365                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11366                a.info.packageName = pkg.applicationInfo.packageName;
11367                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11368                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11369                a.info.splitNames = pkg.splitNames;
11370                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11371                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11372                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11373                a.info.dataDir = pkg.applicationInfo.dataDir;
11374                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11375                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11376                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11377                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11378                mInstrumentation.put(a.getComponentName(), a);
11379                if (chatty) {
11380                    if (r == null) {
11381                        r = new StringBuilder(256);
11382                    } else {
11383                        r.append(' ');
11384                    }
11385                    r.append(a.info.name);
11386                }
11387            }
11388            if (r != null) {
11389                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11390            }
11391
11392            if (pkg.protectedBroadcasts != null) {
11393                N = pkg.protectedBroadcasts.size();
11394                for (i=0; i<N; i++) {
11395                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11396                }
11397            }
11398        }
11399
11400        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11401    }
11402
11403    /**
11404     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11405     * is derived purely on the basis of the contents of {@code scanFile} and
11406     * {@code cpuAbiOverride}.
11407     *
11408     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11409     */
11410    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11411                                 String cpuAbiOverride, boolean extractLibs,
11412                                 File appLib32InstallDir)
11413            throws PackageManagerException {
11414        // Give ourselves some initial paths; we'll come back for another
11415        // pass once we've determined ABI below.
11416        setNativeLibraryPaths(pkg, appLib32InstallDir);
11417
11418        // We would never need to extract libs for forward-locked and external packages,
11419        // since the container service will do it for us. We shouldn't attempt to
11420        // extract libs from system app when it was not updated.
11421        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11422                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11423            extractLibs = false;
11424        }
11425
11426        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11427        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11428
11429        NativeLibraryHelper.Handle handle = null;
11430        try {
11431            handle = NativeLibraryHelper.Handle.create(pkg);
11432            // TODO(multiArch): This can be null for apps that didn't go through the
11433            // usual installation process. We can calculate it again, like we
11434            // do during install time.
11435            //
11436            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11437            // unnecessary.
11438            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11439
11440            // Null out the abis so that they can be recalculated.
11441            pkg.applicationInfo.primaryCpuAbi = null;
11442            pkg.applicationInfo.secondaryCpuAbi = null;
11443            if (isMultiArch(pkg.applicationInfo)) {
11444                // Warn if we've set an abiOverride for multi-lib packages..
11445                // By definition, we need to copy both 32 and 64 bit libraries for
11446                // such packages.
11447                if (pkg.cpuAbiOverride != null
11448                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11449                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11450                }
11451
11452                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11453                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11454                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11455                    if (extractLibs) {
11456                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11457                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11458                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11459                                useIsaSpecificSubdirs);
11460                    } else {
11461                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11462                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11463                    }
11464                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11465                }
11466
11467                // Shared library native code should be in the APK zip aligned
11468                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11469                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11470                            "Shared library native lib extraction not supported");
11471                }
11472
11473                maybeThrowExceptionForMultiArchCopy(
11474                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11475
11476                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11477                    if (extractLibs) {
11478                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11479                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11480                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11481                                useIsaSpecificSubdirs);
11482                    } else {
11483                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11484                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11485                    }
11486                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11487                }
11488
11489                maybeThrowExceptionForMultiArchCopy(
11490                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11491
11492                if (abi64 >= 0) {
11493                    // Shared library native libs should be in the APK zip aligned
11494                    if (extractLibs && pkg.isLibrary()) {
11495                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11496                                "Shared library native lib extraction not supported");
11497                    }
11498                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11499                }
11500
11501                if (abi32 >= 0) {
11502                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11503                    if (abi64 >= 0) {
11504                        if (pkg.use32bitAbi) {
11505                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11506                            pkg.applicationInfo.primaryCpuAbi = abi;
11507                        } else {
11508                            pkg.applicationInfo.secondaryCpuAbi = abi;
11509                        }
11510                    } else {
11511                        pkg.applicationInfo.primaryCpuAbi = abi;
11512                    }
11513                }
11514            } else {
11515                String[] abiList = (cpuAbiOverride != null) ?
11516                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11517
11518                // Enable gross and lame hacks for apps that are built with old
11519                // SDK tools. We must scan their APKs for renderscript bitcode and
11520                // not launch them if it's present. Don't bother checking on devices
11521                // that don't have 64 bit support.
11522                boolean needsRenderScriptOverride = false;
11523                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11524                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11525                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11526                    needsRenderScriptOverride = true;
11527                }
11528
11529                final int copyRet;
11530                if (extractLibs) {
11531                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11532                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11533                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11534                } else {
11535                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11536                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11537                }
11538                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11539
11540                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11541                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11542                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11543                }
11544
11545                if (copyRet >= 0) {
11546                    // Shared libraries that have native libs must be multi-architecture
11547                    if (pkg.isLibrary()) {
11548                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11549                                "Shared library with native libs must be multiarch");
11550                    }
11551                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11552                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11553                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11554                } else if (needsRenderScriptOverride) {
11555                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11556                }
11557            }
11558        } catch (IOException ioe) {
11559            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11560        } finally {
11561            IoUtils.closeQuietly(handle);
11562        }
11563
11564        // Now that we've calculated the ABIs and determined if it's an internal app,
11565        // we will go ahead and populate the nativeLibraryPath.
11566        setNativeLibraryPaths(pkg, appLib32InstallDir);
11567    }
11568
11569    /**
11570     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11571     * i.e, so that all packages can be run inside a single process if required.
11572     *
11573     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11574     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11575     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11576     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11577     * updating a package that belongs to a shared user.
11578     *
11579     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11580     * adds unnecessary complexity.
11581     */
11582    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11583            PackageParser.Package scannedPackage) {
11584        String requiredInstructionSet = null;
11585        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11586            requiredInstructionSet = VMRuntime.getInstructionSet(
11587                     scannedPackage.applicationInfo.primaryCpuAbi);
11588        }
11589
11590        PackageSetting requirer = null;
11591        for (PackageSetting ps : packagesForUser) {
11592            // If packagesForUser contains scannedPackage, we skip it. This will happen
11593            // when scannedPackage is an update of an existing package. Without this check,
11594            // we will never be able to change the ABI of any package belonging to a shared
11595            // user, even if it's compatible with other packages.
11596            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11597                if (ps.primaryCpuAbiString == null) {
11598                    continue;
11599                }
11600
11601                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11602                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11603                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11604                    // this but there's not much we can do.
11605                    String errorMessage = "Instruction set mismatch, "
11606                            + ((requirer == null) ? "[caller]" : requirer)
11607                            + " requires " + requiredInstructionSet + " whereas " + ps
11608                            + " requires " + instructionSet;
11609                    Slog.w(TAG, errorMessage);
11610                }
11611
11612                if (requiredInstructionSet == null) {
11613                    requiredInstructionSet = instructionSet;
11614                    requirer = ps;
11615                }
11616            }
11617        }
11618
11619        if (requiredInstructionSet != null) {
11620            String adjustedAbi;
11621            if (requirer != null) {
11622                // requirer != null implies that either scannedPackage was null or that scannedPackage
11623                // did not require an ABI, in which case we have to adjust scannedPackage to match
11624                // the ABI of the set (which is the same as requirer's ABI)
11625                adjustedAbi = requirer.primaryCpuAbiString;
11626                if (scannedPackage != null) {
11627                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11628                }
11629            } else {
11630                // requirer == null implies that we're updating all ABIs in the set to
11631                // match scannedPackage.
11632                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11633            }
11634
11635            for (PackageSetting ps : packagesForUser) {
11636                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11637                    if (ps.primaryCpuAbiString != null) {
11638                        continue;
11639                    }
11640
11641                    ps.primaryCpuAbiString = adjustedAbi;
11642                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11643                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11644                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11645                        if (DEBUG_ABI_SELECTION) {
11646                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11647                                    + " (requirer="
11648                                    + (requirer != null ? requirer.pkg : "null")
11649                                    + ", scannedPackage="
11650                                    + (scannedPackage != null ? scannedPackage : "null")
11651                                    + ")");
11652                        }
11653                        try {
11654                            mInstaller.rmdex(ps.codePathString,
11655                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11656                        } catch (InstallerException ignored) {
11657                        }
11658                    }
11659                }
11660            }
11661        }
11662    }
11663
11664    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11665        synchronized (mPackages) {
11666            mResolverReplaced = true;
11667            // Set up information for custom user intent resolution activity.
11668            mResolveActivity.applicationInfo = pkg.applicationInfo;
11669            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11670            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11671            mResolveActivity.processName = pkg.applicationInfo.packageName;
11672            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11673            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11674                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11675            mResolveActivity.theme = 0;
11676            mResolveActivity.exported = true;
11677            mResolveActivity.enabled = true;
11678            mResolveInfo.activityInfo = mResolveActivity;
11679            mResolveInfo.priority = 0;
11680            mResolveInfo.preferredOrder = 0;
11681            mResolveInfo.match = 0;
11682            mResolveComponentName = mCustomResolverComponentName;
11683            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11684                    mResolveComponentName);
11685        }
11686    }
11687
11688    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11689        if (installerActivity == null) {
11690            if (DEBUG_EPHEMERAL) {
11691                Slog.d(TAG, "Clear ephemeral installer activity");
11692            }
11693            mInstantAppInstallerActivity = null;
11694            return;
11695        }
11696
11697        if (DEBUG_EPHEMERAL) {
11698            Slog.d(TAG, "Set ephemeral installer activity: "
11699                    + installerActivity.getComponentName());
11700        }
11701        // Set up information for ephemeral installer activity
11702        mInstantAppInstallerActivity = installerActivity;
11703        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11704                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11705        mInstantAppInstallerActivity.exported = true;
11706        mInstantAppInstallerActivity.enabled = true;
11707        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11708        mInstantAppInstallerInfo.priority = 0;
11709        mInstantAppInstallerInfo.preferredOrder = 1;
11710        mInstantAppInstallerInfo.isDefault = true;
11711        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11712                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11713    }
11714
11715    private static String calculateBundledApkRoot(final String codePathString) {
11716        final File codePath = new File(codePathString);
11717        final File codeRoot;
11718        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11719            codeRoot = Environment.getRootDirectory();
11720        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11721            codeRoot = Environment.getOemDirectory();
11722        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11723            codeRoot = Environment.getVendorDirectory();
11724        } else {
11725            // Unrecognized code path; take its top real segment as the apk root:
11726            // e.g. /something/app/blah.apk => /something
11727            try {
11728                File f = codePath.getCanonicalFile();
11729                File parent = f.getParentFile();    // non-null because codePath is a file
11730                File tmp;
11731                while ((tmp = parent.getParentFile()) != null) {
11732                    f = parent;
11733                    parent = tmp;
11734                }
11735                codeRoot = f;
11736                Slog.w(TAG, "Unrecognized code path "
11737                        + codePath + " - using " + codeRoot);
11738            } catch (IOException e) {
11739                // Can't canonicalize the code path -- shenanigans?
11740                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11741                return Environment.getRootDirectory().getPath();
11742            }
11743        }
11744        return codeRoot.getPath();
11745    }
11746
11747    /**
11748     * Derive and set the location of native libraries for the given package,
11749     * which varies depending on where and how the package was installed.
11750     */
11751    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11752        final ApplicationInfo info = pkg.applicationInfo;
11753        final String codePath = pkg.codePath;
11754        final File codeFile = new File(codePath);
11755        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11756        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11757
11758        info.nativeLibraryRootDir = null;
11759        info.nativeLibraryRootRequiresIsa = false;
11760        info.nativeLibraryDir = null;
11761        info.secondaryNativeLibraryDir = null;
11762
11763        if (isApkFile(codeFile)) {
11764            // Monolithic install
11765            if (bundledApp) {
11766                // If "/system/lib64/apkname" exists, assume that is the per-package
11767                // native library directory to use; otherwise use "/system/lib/apkname".
11768                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11769                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11770                        getPrimaryInstructionSet(info));
11771
11772                // This is a bundled system app so choose the path based on the ABI.
11773                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11774                // is just the default path.
11775                final String apkName = deriveCodePathName(codePath);
11776                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11777                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11778                        apkName).getAbsolutePath();
11779
11780                if (info.secondaryCpuAbi != null) {
11781                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11782                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11783                            secondaryLibDir, apkName).getAbsolutePath();
11784                }
11785            } else if (asecApp) {
11786                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11787                        .getAbsolutePath();
11788            } else {
11789                final String apkName = deriveCodePathName(codePath);
11790                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11791                        .getAbsolutePath();
11792            }
11793
11794            info.nativeLibraryRootRequiresIsa = false;
11795            info.nativeLibraryDir = info.nativeLibraryRootDir;
11796        } else {
11797            // Cluster install
11798            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11799            info.nativeLibraryRootRequiresIsa = true;
11800
11801            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11802                    getPrimaryInstructionSet(info)).getAbsolutePath();
11803
11804            if (info.secondaryCpuAbi != null) {
11805                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11806                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11807            }
11808        }
11809    }
11810
11811    /**
11812     * Calculate the abis and roots for a bundled app. These can uniquely
11813     * be determined from the contents of the system partition, i.e whether
11814     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11815     * of this information, and instead assume that the system was built
11816     * sensibly.
11817     */
11818    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11819                                           PackageSetting pkgSetting) {
11820        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11821
11822        // If "/system/lib64/apkname" exists, assume that is the per-package
11823        // native library directory to use; otherwise use "/system/lib/apkname".
11824        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11825        setBundledAppAbi(pkg, apkRoot, apkName);
11826        // pkgSetting might be null during rescan following uninstall of updates
11827        // to a bundled app, so accommodate that possibility.  The settings in
11828        // that case will be established later from the parsed package.
11829        //
11830        // If the settings aren't null, sync them up with what we've just derived.
11831        // note that apkRoot isn't stored in the package settings.
11832        if (pkgSetting != null) {
11833            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11834            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11835        }
11836    }
11837
11838    /**
11839     * Deduces the ABI of a bundled app and sets the relevant fields on the
11840     * parsed pkg object.
11841     *
11842     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11843     *        under which system libraries are installed.
11844     * @param apkName the name of the installed package.
11845     */
11846    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11847        final File codeFile = new File(pkg.codePath);
11848
11849        final boolean has64BitLibs;
11850        final boolean has32BitLibs;
11851        if (isApkFile(codeFile)) {
11852            // Monolithic install
11853            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11854            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11855        } else {
11856            // Cluster install
11857            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11858            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11859                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11860                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11861                has64BitLibs = (new File(rootDir, isa)).exists();
11862            } else {
11863                has64BitLibs = false;
11864            }
11865            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11866                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11867                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11868                has32BitLibs = (new File(rootDir, isa)).exists();
11869            } else {
11870                has32BitLibs = false;
11871            }
11872        }
11873
11874        if (has64BitLibs && !has32BitLibs) {
11875            // The package has 64 bit libs, but not 32 bit libs. Its primary
11876            // ABI should be 64 bit. We can safely assume here that the bundled
11877            // native libraries correspond to the most preferred ABI in the list.
11878
11879            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11880            pkg.applicationInfo.secondaryCpuAbi = null;
11881        } else if (has32BitLibs && !has64BitLibs) {
11882            // The package has 32 bit libs but not 64 bit libs. Its primary
11883            // ABI should be 32 bit.
11884
11885            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11886            pkg.applicationInfo.secondaryCpuAbi = null;
11887        } else if (has32BitLibs && has64BitLibs) {
11888            // The application has both 64 and 32 bit bundled libraries. We check
11889            // here that the app declares multiArch support, and warn if it doesn't.
11890            //
11891            // We will be lenient here and record both ABIs. The primary will be the
11892            // ABI that's higher on the list, i.e, a device that's configured to prefer
11893            // 64 bit apps will see a 64 bit primary ABI,
11894
11895            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11896                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11897            }
11898
11899            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11900                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11901                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11902            } else {
11903                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11904                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11905            }
11906        } else {
11907            pkg.applicationInfo.primaryCpuAbi = null;
11908            pkg.applicationInfo.secondaryCpuAbi = null;
11909        }
11910    }
11911
11912    private void killApplication(String pkgName, int appId, String reason) {
11913        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11914    }
11915
11916    private void killApplication(String pkgName, int appId, int userId, String reason) {
11917        // Request the ActivityManager to kill the process(only for existing packages)
11918        // so that we do not end up in a confused state while the user is still using the older
11919        // version of the application while the new one gets installed.
11920        final long token = Binder.clearCallingIdentity();
11921        try {
11922            IActivityManager am = ActivityManager.getService();
11923            if (am != null) {
11924                try {
11925                    am.killApplication(pkgName, appId, userId, reason);
11926                } catch (RemoteException e) {
11927                }
11928            }
11929        } finally {
11930            Binder.restoreCallingIdentity(token);
11931        }
11932    }
11933
11934    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11935        // Remove the parent package setting
11936        PackageSetting ps = (PackageSetting) pkg.mExtras;
11937        if (ps != null) {
11938            removePackageLI(ps, chatty);
11939        }
11940        // Remove the child package setting
11941        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11942        for (int i = 0; i < childCount; i++) {
11943            PackageParser.Package childPkg = pkg.childPackages.get(i);
11944            ps = (PackageSetting) childPkg.mExtras;
11945            if (ps != null) {
11946                removePackageLI(ps, chatty);
11947            }
11948        }
11949    }
11950
11951    void removePackageLI(PackageSetting ps, boolean chatty) {
11952        if (DEBUG_INSTALL) {
11953            if (chatty)
11954                Log.d(TAG, "Removing package " + ps.name);
11955        }
11956
11957        // writer
11958        synchronized (mPackages) {
11959            mPackages.remove(ps.name);
11960            final PackageParser.Package pkg = ps.pkg;
11961            if (pkg != null) {
11962                cleanPackageDataStructuresLILPw(pkg, chatty);
11963            }
11964        }
11965    }
11966
11967    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11968        if (DEBUG_INSTALL) {
11969            if (chatty)
11970                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11971        }
11972
11973        // writer
11974        synchronized (mPackages) {
11975            // Remove the parent package
11976            mPackages.remove(pkg.applicationInfo.packageName);
11977            cleanPackageDataStructuresLILPw(pkg, chatty);
11978
11979            // Remove the child packages
11980            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11981            for (int i = 0; i < childCount; i++) {
11982                PackageParser.Package childPkg = pkg.childPackages.get(i);
11983                mPackages.remove(childPkg.applicationInfo.packageName);
11984                cleanPackageDataStructuresLILPw(childPkg, chatty);
11985            }
11986        }
11987    }
11988
11989    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11990        int N = pkg.providers.size();
11991        StringBuilder r = null;
11992        int i;
11993        for (i=0; i<N; i++) {
11994            PackageParser.Provider p = pkg.providers.get(i);
11995            mProviders.removeProvider(p);
11996            if (p.info.authority == null) {
11997
11998                /* There was another ContentProvider with this authority when
11999                 * this app was installed so this authority is null,
12000                 * Ignore it as we don't have to unregister the provider.
12001                 */
12002                continue;
12003            }
12004            String names[] = p.info.authority.split(";");
12005            for (int j = 0; j < names.length; j++) {
12006                if (mProvidersByAuthority.get(names[j]) == p) {
12007                    mProvidersByAuthority.remove(names[j]);
12008                    if (DEBUG_REMOVE) {
12009                        if (chatty)
12010                            Log.d(TAG, "Unregistered content provider: " + names[j]
12011                                    + ", className = " + p.info.name + ", isSyncable = "
12012                                    + p.info.isSyncable);
12013                    }
12014                }
12015            }
12016            if (DEBUG_REMOVE && chatty) {
12017                if (r == null) {
12018                    r = new StringBuilder(256);
12019                } else {
12020                    r.append(' ');
12021                }
12022                r.append(p.info.name);
12023            }
12024        }
12025        if (r != null) {
12026            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12027        }
12028
12029        N = pkg.services.size();
12030        r = null;
12031        for (i=0; i<N; i++) {
12032            PackageParser.Service s = pkg.services.get(i);
12033            mServices.removeService(s);
12034            if (chatty) {
12035                if (r == null) {
12036                    r = new StringBuilder(256);
12037                } else {
12038                    r.append(' ');
12039                }
12040                r.append(s.info.name);
12041            }
12042        }
12043        if (r != null) {
12044            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12045        }
12046
12047        N = pkg.receivers.size();
12048        r = null;
12049        for (i=0; i<N; i++) {
12050            PackageParser.Activity a = pkg.receivers.get(i);
12051            mReceivers.removeActivity(a, "receiver");
12052            if (DEBUG_REMOVE && chatty) {
12053                if (r == null) {
12054                    r = new StringBuilder(256);
12055                } else {
12056                    r.append(' ');
12057                }
12058                r.append(a.info.name);
12059            }
12060        }
12061        if (r != null) {
12062            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12063        }
12064
12065        N = pkg.activities.size();
12066        r = null;
12067        for (i=0; i<N; i++) {
12068            PackageParser.Activity a = pkg.activities.get(i);
12069            mActivities.removeActivity(a, "activity");
12070            if (DEBUG_REMOVE && chatty) {
12071                if (r == null) {
12072                    r = new StringBuilder(256);
12073                } else {
12074                    r.append(' ');
12075                }
12076                r.append(a.info.name);
12077            }
12078        }
12079        if (r != null) {
12080            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12081        }
12082
12083        N = pkg.permissions.size();
12084        r = null;
12085        for (i=0; i<N; i++) {
12086            PackageParser.Permission p = pkg.permissions.get(i);
12087            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12088            if (bp == null) {
12089                bp = mSettings.mPermissionTrees.get(p.info.name);
12090            }
12091            if (bp != null && bp.perm == p) {
12092                bp.perm = null;
12093                if (DEBUG_REMOVE && chatty) {
12094                    if (r == null) {
12095                        r = new StringBuilder(256);
12096                    } else {
12097                        r.append(' ');
12098                    }
12099                    r.append(p.info.name);
12100                }
12101            }
12102            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12103                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12104                if (appOpPkgs != null) {
12105                    appOpPkgs.remove(pkg.packageName);
12106                }
12107            }
12108        }
12109        if (r != null) {
12110            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12111        }
12112
12113        N = pkg.requestedPermissions.size();
12114        r = null;
12115        for (i=0; i<N; i++) {
12116            String perm = pkg.requestedPermissions.get(i);
12117            BasePermission bp = mSettings.mPermissions.get(perm);
12118            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12119                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12120                if (appOpPkgs != null) {
12121                    appOpPkgs.remove(pkg.packageName);
12122                    if (appOpPkgs.isEmpty()) {
12123                        mAppOpPermissionPackages.remove(perm);
12124                    }
12125                }
12126            }
12127        }
12128        if (r != null) {
12129            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12130        }
12131
12132        N = pkg.instrumentation.size();
12133        r = null;
12134        for (i=0; i<N; i++) {
12135            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12136            mInstrumentation.remove(a.getComponentName());
12137            if (DEBUG_REMOVE && chatty) {
12138                if (r == null) {
12139                    r = new StringBuilder(256);
12140                } else {
12141                    r.append(' ');
12142                }
12143                r.append(a.info.name);
12144            }
12145        }
12146        if (r != null) {
12147            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12148        }
12149
12150        r = null;
12151        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12152            // Only system apps can hold shared libraries.
12153            if (pkg.libraryNames != null) {
12154                for (i = 0; i < pkg.libraryNames.size(); i++) {
12155                    String name = pkg.libraryNames.get(i);
12156                    if (removeSharedLibraryLPw(name, 0)) {
12157                        if (DEBUG_REMOVE && chatty) {
12158                            if (r == null) {
12159                                r = new StringBuilder(256);
12160                            } else {
12161                                r.append(' ');
12162                            }
12163                            r.append(name);
12164                        }
12165                    }
12166                }
12167            }
12168        }
12169
12170        r = null;
12171
12172        // Any package can hold static shared libraries.
12173        if (pkg.staticSharedLibName != null) {
12174            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12175                if (DEBUG_REMOVE && chatty) {
12176                    if (r == null) {
12177                        r = new StringBuilder(256);
12178                    } else {
12179                        r.append(' ');
12180                    }
12181                    r.append(pkg.staticSharedLibName);
12182                }
12183            }
12184        }
12185
12186        if (r != null) {
12187            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12188        }
12189    }
12190
12191    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12192        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12193            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12194                return true;
12195            }
12196        }
12197        return false;
12198    }
12199
12200    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12201    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12202    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12203
12204    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12205        // Update the parent permissions
12206        updatePermissionsLPw(pkg.packageName, pkg, flags);
12207        // Update the child permissions
12208        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12209        for (int i = 0; i < childCount; i++) {
12210            PackageParser.Package childPkg = pkg.childPackages.get(i);
12211            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12212        }
12213    }
12214
12215    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12216            int flags) {
12217        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12218        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12219    }
12220
12221    private void updatePermissionsLPw(String changingPkg,
12222            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12223        // Make sure there are no dangling permission trees.
12224        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12225        while (it.hasNext()) {
12226            final BasePermission bp = it.next();
12227            if (bp.packageSetting == null) {
12228                // We may not yet have parsed the package, so just see if
12229                // we still know about its settings.
12230                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12231            }
12232            if (bp.packageSetting == null) {
12233                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12234                        + " from package " + bp.sourcePackage);
12235                it.remove();
12236            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12237                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12238                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12239                            + " from package " + bp.sourcePackage);
12240                    flags |= UPDATE_PERMISSIONS_ALL;
12241                    it.remove();
12242                }
12243            }
12244        }
12245
12246        // Make sure all dynamic permissions have been assigned to a package,
12247        // and make sure there are no dangling permissions.
12248        it = mSettings.mPermissions.values().iterator();
12249        while (it.hasNext()) {
12250            final BasePermission bp = it.next();
12251            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12252                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12253                        + bp.name + " pkg=" + bp.sourcePackage
12254                        + " info=" + bp.pendingInfo);
12255                if (bp.packageSetting == null && bp.pendingInfo != null) {
12256                    final BasePermission tree = findPermissionTreeLP(bp.name);
12257                    if (tree != null && tree.perm != null) {
12258                        bp.packageSetting = tree.packageSetting;
12259                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12260                                new PermissionInfo(bp.pendingInfo));
12261                        bp.perm.info.packageName = tree.perm.info.packageName;
12262                        bp.perm.info.name = bp.name;
12263                        bp.uid = tree.uid;
12264                    }
12265                }
12266            }
12267            if (bp.packageSetting == null) {
12268                // We may not yet have parsed the package, so just see if
12269                // we still know about its settings.
12270                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12271            }
12272            if (bp.packageSetting == null) {
12273                Slog.w(TAG, "Removing dangling permission: " + bp.name
12274                        + " from package " + bp.sourcePackage);
12275                it.remove();
12276            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12277                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12278                    Slog.i(TAG, "Removing old permission: " + bp.name
12279                            + " from package " + bp.sourcePackage);
12280                    flags |= UPDATE_PERMISSIONS_ALL;
12281                    it.remove();
12282                }
12283            }
12284        }
12285
12286        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12287        // Now update the permissions for all packages, in particular
12288        // replace the granted permissions of the system packages.
12289        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12290            for (PackageParser.Package pkg : mPackages.values()) {
12291                if (pkg != pkgInfo) {
12292                    // Only replace for packages on requested volume
12293                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12294                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12295                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12296                    grantPermissionsLPw(pkg, replace, changingPkg);
12297                }
12298            }
12299        }
12300
12301        if (pkgInfo != null) {
12302            // Only replace for packages on requested volume
12303            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12304            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12305                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12306            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12307        }
12308        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12309    }
12310
12311    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12312            String packageOfInterest) {
12313        // IMPORTANT: There are two types of permissions: install and runtime.
12314        // Install time permissions are granted when the app is installed to
12315        // all device users and users added in the future. Runtime permissions
12316        // are granted at runtime explicitly to specific users. Normal and signature
12317        // protected permissions are install time permissions. Dangerous permissions
12318        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12319        // otherwise they are runtime permissions. This function does not manage
12320        // runtime permissions except for the case an app targeting Lollipop MR1
12321        // being upgraded to target a newer SDK, in which case dangerous permissions
12322        // are transformed from install time to runtime ones.
12323
12324        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12325        if (ps == null) {
12326            return;
12327        }
12328
12329        PermissionsState permissionsState = ps.getPermissionsState();
12330        PermissionsState origPermissions = permissionsState;
12331
12332        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12333
12334        boolean runtimePermissionsRevoked = false;
12335        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12336
12337        boolean changedInstallPermission = false;
12338
12339        if (replace) {
12340            ps.installPermissionsFixed = false;
12341            if (!ps.isSharedUser()) {
12342                origPermissions = new PermissionsState(permissionsState);
12343                permissionsState.reset();
12344            } else {
12345                // We need to know only about runtime permission changes since the
12346                // calling code always writes the install permissions state but
12347                // the runtime ones are written only if changed. The only cases of
12348                // changed runtime permissions here are promotion of an install to
12349                // runtime and revocation of a runtime from a shared user.
12350                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12351                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12352                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12353                    runtimePermissionsRevoked = true;
12354                }
12355            }
12356        }
12357
12358        permissionsState.setGlobalGids(mGlobalGids);
12359
12360        final int N = pkg.requestedPermissions.size();
12361        for (int i=0; i<N; i++) {
12362            final String name = pkg.requestedPermissions.get(i);
12363            final BasePermission bp = mSettings.mPermissions.get(name);
12364            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12365                    >= Build.VERSION_CODES.M;
12366
12367            if (DEBUG_INSTALL) {
12368                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12369            }
12370
12371            if (bp == null || bp.packageSetting == null) {
12372                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12373                    if (DEBUG_PERMISSIONS) {
12374                        Slog.i(TAG, "Unknown permission " + name
12375                                + " in package " + pkg.packageName);
12376                    }
12377                }
12378                continue;
12379            }
12380
12381
12382            // Limit ephemeral apps to ephemeral allowed permissions.
12383            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12384                if (DEBUG_PERMISSIONS) {
12385                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12386                            + pkg.packageName);
12387                }
12388                continue;
12389            }
12390
12391            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12392                if (DEBUG_PERMISSIONS) {
12393                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12394                            + pkg.packageName);
12395                }
12396                continue;
12397            }
12398
12399            final String perm = bp.name;
12400            boolean allowedSig = false;
12401            int grant = GRANT_DENIED;
12402
12403            // Keep track of app op permissions.
12404            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12405                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12406                if (pkgs == null) {
12407                    pkgs = new ArraySet<>();
12408                    mAppOpPermissionPackages.put(bp.name, pkgs);
12409                }
12410                pkgs.add(pkg.packageName);
12411            }
12412
12413            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12414            switch (level) {
12415                case PermissionInfo.PROTECTION_NORMAL: {
12416                    // For all apps normal permissions are install time ones.
12417                    grant = GRANT_INSTALL;
12418                } break;
12419
12420                case PermissionInfo.PROTECTION_DANGEROUS: {
12421                    // If a permission review is required for legacy apps we represent
12422                    // their permissions as always granted runtime ones since we need
12423                    // to keep the review required permission flag per user while an
12424                    // install permission's state is shared across all users.
12425                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12426                        // For legacy apps dangerous permissions are install time ones.
12427                        grant = GRANT_INSTALL;
12428                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12429                        // For legacy apps that became modern, install becomes runtime.
12430                        grant = GRANT_UPGRADE;
12431                    } else if (mPromoteSystemApps
12432                            && isSystemApp(ps)
12433                            && mExistingSystemPackages.contains(ps.name)) {
12434                        // For legacy system apps, install becomes runtime.
12435                        // We cannot check hasInstallPermission() for system apps since those
12436                        // permissions were granted implicitly and not persisted pre-M.
12437                        grant = GRANT_UPGRADE;
12438                    } else {
12439                        // For modern apps keep runtime permissions unchanged.
12440                        grant = GRANT_RUNTIME;
12441                    }
12442                } break;
12443
12444                case PermissionInfo.PROTECTION_SIGNATURE: {
12445                    // For all apps signature permissions are install time ones.
12446                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12447                    if (allowedSig) {
12448                        grant = GRANT_INSTALL;
12449                    }
12450                } break;
12451            }
12452
12453            if (DEBUG_PERMISSIONS) {
12454                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12455            }
12456
12457            if (grant != GRANT_DENIED) {
12458                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12459                    // If this is an existing, non-system package, then
12460                    // we can't add any new permissions to it.
12461                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12462                        // Except...  if this is a permission that was added
12463                        // to the platform (note: need to only do this when
12464                        // updating the platform).
12465                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12466                            grant = GRANT_DENIED;
12467                        }
12468                    }
12469                }
12470
12471                switch (grant) {
12472                    case GRANT_INSTALL: {
12473                        // Revoke this as runtime permission to handle the case of
12474                        // a runtime permission being downgraded to an install one.
12475                        // Also in permission review mode we keep dangerous permissions
12476                        // for legacy apps
12477                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12478                            if (origPermissions.getRuntimePermissionState(
12479                                    bp.name, userId) != null) {
12480                                // Revoke the runtime permission and clear the flags.
12481                                origPermissions.revokeRuntimePermission(bp, userId);
12482                                origPermissions.updatePermissionFlags(bp, userId,
12483                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12484                                // If we revoked a permission permission, we have to write.
12485                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12486                                        changedRuntimePermissionUserIds, userId);
12487                            }
12488                        }
12489                        // Grant an install permission.
12490                        if (permissionsState.grantInstallPermission(bp) !=
12491                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12492                            changedInstallPermission = true;
12493                        }
12494                    } break;
12495
12496                    case GRANT_RUNTIME: {
12497                        // Grant previously granted runtime permissions.
12498                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12499                            PermissionState permissionState = origPermissions
12500                                    .getRuntimePermissionState(bp.name, userId);
12501                            int flags = permissionState != null
12502                                    ? permissionState.getFlags() : 0;
12503                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12504                                // Don't propagate the permission in a permission review mode if
12505                                // the former was revoked, i.e. marked to not propagate on upgrade.
12506                                // Note that in a permission review mode install permissions are
12507                                // represented as constantly granted runtime ones since we need to
12508                                // keep a per user state associated with the permission. Also the
12509                                // revoke on upgrade flag is no longer applicable and is reset.
12510                                final boolean revokeOnUpgrade = (flags & PackageManager
12511                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12512                                if (revokeOnUpgrade) {
12513                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12514                                    // Since we changed the flags, we have to write.
12515                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12516                                            changedRuntimePermissionUserIds, userId);
12517                                }
12518                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12519                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12520                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12521                                        // If we cannot put the permission as it was,
12522                                        // we have to write.
12523                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12524                                                changedRuntimePermissionUserIds, userId);
12525                                    }
12526                                }
12527
12528                                // If the app supports runtime permissions no need for a review.
12529                                if (mPermissionReviewRequired
12530                                        && appSupportsRuntimePermissions
12531                                        && (flags & PackageManager
12532                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12533                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12534                                    // Since we changed the flags, we have to write.
12535                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12536                                            changedRuntimePermissionUserIds, userId);
12537                                }
12538                            } else if (mPermissionReviewRequired
12539                                    && !appSupportsRuntimePermissions) {
12540                                // For legacy apps that need a permission review, every new
12541                                // runtime permission is granted but it is pending a review.
12542                                // We also need to review only platform defined runtime
12543                                // permissions as these are the only ones the platform knows
12544                                // how to disable the API to simulate revocation as legacy
12545                                // apps don't expect to run with revoked permissions.
12546                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12547                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12548                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12549                                        // We changed the flags, hence have to write.
12550                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12551                                                changedRuntimePermissionUserIds, userId);
12552                                    }
12553                                }
12554                                if (permissionsState.grantRuntimePermission(bp, userId)
12555                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12556                                    // We changed the permission, hence have to write.
12557                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12558                                            changedRuntimePermissionUserIds, userId);
12559                                }
12560                            }
12561                            // Propagate the permission flags.
12562                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12563                        }
12564                    } break;
12565
12566                    case GRANT_UPGRADE: {
12567                        // Grant runtime permissions for a previously held install permission.
12568                        PermissionState permissionState = origPermissions
12569                                .getInstallPermissionState(bp.name);
12570                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12571
12572                        if (origPermissions.revokeInstallPermission(bp)
12573                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12574                            // We will be transferring the permission flags, so clear them.
12575                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12576                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12577                            changedInstallPermission = true;
12578                        }
12579
12580                        // If the permission is not to be promoted to runtime we ignore it and
12581                        // also its other flags as they are not applicable to install permissions.
12582                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12583                            for (int userId : currentUserIds) {
12584                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12585                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12586                                    // Transfer the permission flags.
12587                                    permissionsState.updatePermissionFlags(bp, userId,
12588                                            flags, flags);
12589                                    // If we granted the permission, we have to write.
12590                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12591                                            changedRuntimePermissionUserIds, userId);
12592                                }
12593                            }
12594                        }
12595                    } break;
12596
12597                    default: {
12598                        if (packageOfInterest == null
12599                                || packageOfInterest.equals(pkg.packageName)) {
12600                            if (DEBUG_PERMISSIONS) {
12601                                Slog.i(TAG, "Not granting permission " + perm
12602                                        + " to package " + pkg.packageName
12603                                        + " because it was previously installed without");
12604                            }
12605                        }
12606                    } break;
12607                }
12608            } else {
12609                if (permissionsState.revokeInstallPermission(bp) !=
12610                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12611                    // Also drop the permission flags.
12612                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12613                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12614                    changedInstallPermission = true;
12615                    Slog.i(TAG, "Un-granting permission " + perm
12616                            + " from package " + pkg.packageName
12617                            + " (protectionLevel=" + bp.protectionLevel
12618                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12619                            + ")");
12620                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12621                    // Don't print warning for app op permissions, since it is fine for them
12622                    // not to be granted, there is a UI for the user to decide.
12623                    if (DEBUG_PERMISSIONS
12624                            && (packageOfInterest == null
12625                                    || packageOfInterest.equals(pkg.packageName))) {
12626                        Slog.i(TAG, "Not granting permission " + perm
12627                                + " to package " + pkg.packageName
12628                                + " (protectionLevel=" + bp.protectionLevel
12629                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12630                                + ")");
12631                    }
12632                }
12633            }
12634        }
12635
12636        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12637                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12638            // This is the first that we have heard about this package, so the
12639            // permissions we have now selected are fixed until explicitly
12640            // changed.
12641            ps.installPermissionsFixed = true;
12642        }
12643
12644        // Persist the runtime permissions state for users with changes. If permissions
12645        // were revoked because no app in the shared user declares them we have to
12646        // write synchronously to avoid losing runtime permissions state.
12647        for (int userId : changedRuntimePermissionUserIds) {
12648            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12649        }
12650    }
12651
12652    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12653        boolean allowed = false;
12654        final int NP = PackageParser.NEW_PERMISSIONS.length;
12655        for (int ip=0; ip<NP; ip++) {
12656            final PackageParser.NewPermissionInfo npi
12657                    = PackageParser.NEW_PERMISSIONS[ip];
12658            if (npi.name.equals(perm)
12659                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12660                allowed = true;
12661                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12662                        + pkg.packageName);
12663                break;
12664            }
12665        }
12666        return allowed;
12667    }
12668
12669    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12670            BasePermission bp, PermissionsState origPermissions) {
12671        boolean privilegedPermission = (bp.protectionLevel
12672                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12673        boolean privappPermissionsDisable =
12674                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12675        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12676        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12677        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12678                && !platformPackage && platformPermission) {
12679            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12680                    .getPrivAppPermissions(pkg.packageName);
12681            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12682            if (!whitelisted) {
12683                Slog.w(TAG, "Privileged permission " + perm + " for package "
12684                        + pkg.packageName + " - not in privapp-permissions whitelist");
12685                // Only report violations for apps on system image
12686                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12687                    if (mPrivappPermissionsViolations == null) {
12688                        mPrivappPermissionsViolations = new ArraySet<>();
12689                    }
12690                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12691                }
12692                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12693                    return false;
12694                }
12695            }
12696        }
12697        boolean allowed = (compareSignatures(
12698                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12699                        == PackageManager.SIGNATURE_MATCH)
12700                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12701                        == PackageManager.SIGNATURE_MATCH);
12702        if (!allowed && privilegedPermission) {
12703            if (isSystemApp(pkg)) {
12704                // For updated system applications, a system permission
12705                // is granted only if it had been defined by the original application.
12706                if (pkg.isUpdatedSystemApp()) {
12707                    final PackageSetting sysPs = mSettings
12708                            .getDisabledSystemPkgLPr(pkg.packageName);
12709                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12710                        // If the original was granted this permission, we take
12711                        // that grant decision as read and propagate it to the
12712                        // update.
12713                        if (sysPs.isPrivileged()) {
12714                            allowed = true;
12715                        }
12716                    } else {
12717                        // The system apk may have been updated with an older
12718                        // version of the one on the data partition, but which
12719                        // granted a new system permission that it didn't have
12720                        // before.  In this case we do want to allow the app to
12721                        // now get the new permission if the ancestral apk is
12722                        // privileged to get it.
12723                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12724                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12725                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12726                                    allowed = true;
12727                                    break;
12728                                }
12729                            }
12730                        }
12731                        // Also if a privileged parent package on the system image or any of
12732                        // its children requested a privileged permission, the updated child
12733                        // packages can also get the permission.
12734                        if (pkg.parentPackage != null) {
12735                            final PackageSetting disabledSysParentPs = mSettings
12736                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12737                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12738                                    && disabledSysParentPs.isPrivileged()) {
12739                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12740                                    allowed = true;
12741                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12742                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12743                                    for (int i = 0; i < count; i++) {
12744                                        PackageParser.Package disabledSysChildPkg =
12745                                                disabledSysParentPs.pkg.childPackages.get(i);
12746                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12747                                                perm)) {
12748                                            allowed = true;
12749                                            break;
12750                                        }
12751                                    }
12752                                }
12753                            }
12754                        }
12755                    }
12756                } else {
12757                    allowed = isPrivilegedApp(pkg);
12758                }
12759            }
12760        }
12761        if (!allowed) {
12762            if (!allowed && (bp.protectionLevel
12763                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12764                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12765                // If this was a previously normal/dangerous permission that got moved
12766                // to a system permission as part of the runtime permission redesign, then
12767                // we still want to blindly grant it to old apps.
12768                allowed = true;
12769            }
12770            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12771                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12772                // If this permission is to be granted to the system installer and
12773                // this app is an installer, then it gets the permission.
12774                allowed = true;
12775            }
12776            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12777                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12778                // If this permission is to be granted to the system verifier and
12779                // this app is a verifier, then it gets the permission.
12780                allowed = true;
12781            }
12782            if (!allowed && (bp.protectionLevel
12783                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12784                    && isSystemApp(pkg)) {
12785                // Any pre-installed system app is allowed to get this permission.
12786                allowed = true;
12787            }
12788            if (!allowed && (bp.protectionLevel
12789                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12790                // For development permissions, a development permission
12791                // is granted only if it was already granted.
12792                allowed = origPermissions.hasInstallPermission(perm);
12793            }
12794            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12795                    && pkg.packageName.equals(mSetupWizardPackage)) {
12796                // If this permission is to be granted to the system setup wizard and
12797                // this app is a setup wizard, then it gets the permission.
12798                allowed = true;
12799            }
12800        }
12801        return allowed;
12802    }
12803
12804    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12805        final int permCount = pkg.requestedPermissions.size();
12806        for (int j = 0; j < permCount; j++) {
12807            String requestedPermission = pkg.requestedPermissions.get(j);
12808            if (permission.equals(requestedPermission)) {
12809                return true;
12810            }
12811        }
12812        return false;
12813    }
12814
12815    final class ActivityIntentResolver
12816            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12817        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12818                boolean defaultOnly, int userId) {
12819            if (!sUserManager.exists(userId)) return null;
12820            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12821            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12822        }
12823
12824        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12825                int userId) {
12826            if (!sUserManager.exists(userId)) return null;
12827            mFlags = flags;
12828            return super.queryIntent(intent, resolvedType,
12829                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12830                    userId);
12831        }
12832
12833        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12834                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12835            if (!sUserManager.exists(userId)) return null;
12836            if (packageActivities == null) {
12837                return null;
12838            }
12839            mFlags = flags;
12840            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12841            final int N = packageActivities.size();
12842            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12843                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12844
12845            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12846            for (int i = 0; i < N; ++i) {
12847                intentFilters = packageActivities.get(i).intents;
12848                if (intentFilters != null && intentFilters.size() > 0) {
12849                    PackageParser.ActivityIntentInfo[] array =
12850                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12851                    intentFilters.toArray(array);
12852                    listCut.add(array);
12853                }
12854            }
12855            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12856        }
12857
12858        /**
12859         * Finds a privileged activity that matches the specified activity names.
12860         */
12861        private PackageParser.Activity findMatchingActivity(
12862                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12863            for (PackageParser.Activity sysActivity : activityList) {
12864                if (sysActivity.info.name.equals(activityInfo.name)) {
12865                    return sysActivity;
12866                }
12867                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12868                    return sysActivity;
12869                }
12870                if (sysActivity.info.targetActivity != null) {
12871                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12872                        return sysActivity;
12873                    }
12874                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12875                        return sysActivity;
12876                    }
12877                }
12878            }
12879            return null;
12880        }
12881
12882        public class IterGenerator<E> {
12883            public Iterator<E> generate(ActivityIntentInfo info) {
12884                return null;
12885            }
12886        }
12887
12888        public class ActionIterGenerator extends IterGenerator<String> {
12889            @Override
12890            public Iterator<String> generate(ActivityIntentInfo info) {
12891                return info.actionsIterator();
12892            }
12893        }
12894
12895        public class CategoriesIterGenerator extends IterGenerator<String> {
12896            @Override
12897            public Iterator<String> generate(ActivityIntentInfo info) {
12898                return info.categoriesIterator();
12899            }
12900        }
12901
12902        public class SchemesIterGenerator extends IterGenerator<String> {
12903            @Override
12904            public Iterator<String> generate(ActivityIntentInfo info) {
12905                return info.schemesIterator();
12906            }
12907        }
12908
12909        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12910            @Override
12911            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12912                return info.authoritiesIterator();
12913            }
12914        }
12915
12916        /**
12917         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12918         * MODIFIED. Do not pass in a list that should not be changed.
12919         */
12920        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12921                IterGenerator<T> generator, Iterator<T> searchIterator) {
12922            // loop through the set of actions; every one must be found in the intent filter
12923            while (searchIterator.hasNext()) {
12924                // we must have at least one filter in the list to consider a match
12925                if (intentList.size() == 0) {
12926                    break;
12927                }
12928
12929                final T searchAction = searchIterator.next();
12930
12931                // loop through the set of intent filters
12932                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12933                while (intentIter.hasNext()) {
12934                    final ActivityIntentInfo intentInfo = intentIter.next();
12935                    boolean selectionFound = false;
12936
12937                    // loop through the intent filter's selection criteria; at least one
12938                    // of them must match the searched criteria
12939                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12940                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12941                        final T intentSelection = intentSelectionIter.next();
12942                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12943                            selectionFound = true;
12944                            break;
12945                        }
12946                    }
12947
12948                    // the selection criteria wasn't found in this filter's set; this filter
12949                    // is not a potential match
12950                    if (!selectionFound) {
12951                        intentIter.remove();
12952                    }
12953                }
12954            }
12955        }
12956
12957        private boolean isProtectedAction(ActivityIntentInfo filter) {
12958            final Iterator<String> actionsIter = filter.actionsIterator();
12959            while (actionsIter != null && actionsIter.hasNext()) {
12960                final String filterAction = actionsIter.next();
12961                if (PROTECTED_ACTIONS.contains(filterAction)) {
12962                    return true;
12963                }
12964            }
12965            return false;
12966        }
12967
12968        /**
12969         * Adjusts the priority of the given intent filter according to policy.
12970         * <p>
12971         * <ul>
12972         * <li>The priority for non privileged applications is capped to '0'</li>
12973         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12974         * <li>The priority for unbundled updates to privileged applications is capped to the
12975         *      priority defined on the system partition</li>
12976         * </ul>
12977         * <p>
12978         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12979         * allowed to obtain any priority on any action.
12980         */
12981        private void adjustPriority(
12982                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12983            // nothing to do; priority is fine as-is
12984            if (intent.getPriority() <= 0) {
12985                return;
12986            }
12987
12988            final ActivityInfo activityInfo = intent.activity.info;
12989            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12990
12991            final boolean privilegedApp =
12992                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12993            if (!privilegedApp) {
12994                // non-privileged applications can never define a priority >0
12995                if (DEBUG_FILTERS) {
12996                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12997                            + " package: " + applicationInfo.packageName
12998                            + " activity: " + intent.activity.className
12999                            + " origPrio: " + intent.getPriority());
13000                }
13001                intent.setPriority(0);
13002                return;
13003            }
13004
13005            if (systemActivities == null) {
13006                // the system package is not disabled; we're parsing the system partition
13007                if (isProtectedAction(intent)) {
13008                    if (mDeferProtectedFilters) {
13009                        // We can't deal with these just yet. No component should ever obtain a
13010                        // >0 priority for a protected actions, with ONE exception -- the setup
13011                        // wizard. The setup wizard, however, cannot be known until we're able to
13012                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13013                        // until all intent filters have been processed. Chicken, meet egg.
13014                        // Let the filter temporarily have a high priority and rectify the
13015                        // priorities after all system packages have been scanned.
13016                        mProtectedFilters.add(intent);
13017                        if (DEBUG_FILTERS) {
13018                            Slog.i(TAG, "Protected action; save for later;"
13019                                    + " package: " + applicationInfo.packageName
13020                                    + " activity: " + intent.activity.className
13021                                    + " origPrio: " + intent.getPriority());
13022                        }
13023                        return;
13024                    } else {
13025                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13026                            Slog.i(TAG, "No setup wizard;"
13027                                + " All protected intents capped to priority 0");
13028                        }
13029                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13030                            if (DEBUG_FILTERS) {
13031                                Slog.i(TAG, "Found setup wizard;"
13032                                    + " allow priority " + intent.getPriority() + ";"
13033                                    + " package: " + intent.activity.info.packageName
13034                                    + " activity: " + intent.activity.className
13035                                    + " priority: " + intent.getPriority());
13036                            }
13037                            // setup wizard gets whatever it wants
13038                            return;
13039                        }
13040                        if (DEBUG_FILTERS) {
13041                            Slog.i(TAG, "Protected action; cap priority to 0;"
13042                                    + " package: " + intent.activity.info.packageName
13043                                    + " activity: " + intent.activity.className
13044                                    + " origPrio: " + intent.getPriority());
13045                        }
13046                        intent.setPriority(0);
13047                        return;
13048                    }
13049                }
13050                // privileged apps on the system image get whatever priority they request
13051                return;
13052            }
13053
13054            // privileged app unbundled update ... try to find the same activity
13055            final PackageParser.Activity foundActivity =
13056                    findMatchingActivity(systemActivities, activityInfo);
13057            if (foundActivity == null) {
13058                // this is a new activity; it cannot obtain >0 priority
13059                if (DEBUG_FILTERS) {
13060                    Slog.i(TAG, "New activity; cap priority to 0;"
13061                            + " package: " + applicationInfo.packageName
13062                            + " activity: " + intent.activity.className
13063                            + " origPrio: " + intent.getPriority());
13064                }
13065                intent.setPriority(0);
13066                return;
13067            }
13068
13069            // found activity, now check for filter equivalence
13070
13071            // a shallow copy is enough; we modify the list, not its contents
13072            final List<ActivityIntentInfo> intentListCopy =
13073                    new ArrayList<>(foundActivity.intents);
13074            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13075
13076            // find matching action subsets
13077            final Iterator<String> actionsIterator = intent.actionsIterator();
13078            if (actionsIterator != null) {
13079                getIntentListSubset(
13080                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13081                if (intentListCopy.size() == 0) {
13082                    // no more intents to match; we're not equivalent
13083                    if (DEBUG_FILTERS) {
13084                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13085                                + " package: " + applicationInfo.packageName
13086                                + " activity: " + intent.activity.className
13087                                + " origPrio: " + intent.getPriority());
13088                    }
13089                    intent.setPriority(0);
13090                    return;
13091                }
13092            }
13093
13094            // find matching category subsets
13095            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13096            if (categoriesIterator != null) {
13097                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13098                        categoriesIterator);
13099                if (intentListCopy.size() == 0) {
13100                    // no more intents to match; we're not equivalent
13101                    if (DEBUG_FILTERS) {
13102                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13103                                + " package: " + applicationInfo.packageName
13104                                + " activity: " + intent.activity.className
13105                                + " origPrio: " + intent.getPriority());
13106                    }
13107                    intent.setPriority(0);
13108                    return;
13109                }
13110            }
13111
13112            // find matching schemes subsets
13113            final Iterator<String> schemesIterator = intent.schemesIterator();
13114            if (schemesIterator != null) {
13115                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13116                        schemesIterator);
13117                if (intentListCopy.size() == 0) {
13118                    // no more intents to match; we're not equivalent
13119                    if (DEBUG_FILTERS) {
13120                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13121                                + " package: " + applicationInfo.packageName
13122                                + " activity: " + intent.activity.className
13123                                + " origPrio: " + intent.getPriority());
13124                    }
13125                    intent.setPriority(0);
13126                    return;
13127                }
13128            }
13129
13130            // find matching authorities subsets
13131            final Iterator<IntentFilter.AuthorityEntry>
13132                    authoritiesIterator = intent.authoritiesIterator();
13133            if (authoritiesIterator != null) {
13134                getIntentListSubset(intentListCopy,
13135                        new AuthoritiesIterGenerator(),
13136                        authoritiesIterator);
13137                if (intentListCopy.size() == 0) {
13138                    // no more intents to match; we're not equivalent
13139                    if (DEBUG_FILTERS) {
13140                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13141                                + " package: " + applicationInfo.packageName
13142                                + " activity: " + intent.activity.className
13143                                + " origPrio: " + intent.getPriority());
13144                    }
13145                    intent.setPriority(0);
13146                    return;
13147                }
13148            }
13149
13150            // we found matching filter(s); app gets the max priority of all intents
13151            int cappedPriority = 0;
13152            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13153                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13154            }
13155            if (intent.getPriority() > cappedPriority) {
13156                if (DEBUG_FILTERS) {
13157                    Slog.i(TAG, "Found matching filter(s);"
13158                            + " cap priority to " + cappedPriority + ";"
13159                            + " package: " + applicationInfo.packageName
13160                            + " activity: " + intent.activity.className
13161                            + " origPrio: " + intent.getPriority());
13162                }
13163                intent.setPriority(cappedPriority);
13164                return;
13165            }
13166            // all this for nothing; the requested priority was <= what was on the system
13167        }
13168
13169        public final void addActivity(PackageParser.Activity a, String type) {
13170            mActivities.put(a.getComponentName(), a);
13171            if (DEBUG_SHOW_INFO)
13172                Log.v(
13173                TAG, "  " + type + " " +
13174                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13175            if (DEBUG_SHOW_INFO)
13176                Log.v(TAG, "    Class=" + a.info.name);
13177            final int NI = a.intents.size();
13178            for (int j=0; j<NI; j++) {
13179                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13180                if ("activity".equals(type)) {
13181                    final PackageSetting ps =
13182                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13183                    final List<PackageParser.Activity> systemActivities =
13184                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13185                    adjustPriority(systemActivities, intent);
13186                }
13187                if (DEBUG_SHOW_INFO) {
13188                    Log.v(TAG, "    IntentFilter:");
13189                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13190                }
13191                if (!intent.debugCheck()) {
13192                    Log.w(TAG, "==> For Activity " + a.info.name);
13193                }
13194                addFilter(intent);
13195            }
13196        }
13197
13198        public final void removeActivity(PackageParser.Activity a, String type) {
13199            mActivities.remove(a.getComponentName());
13200            if (DEBUG_SHOW_INFO) {
13201                Log.v(TAG, "  " + type + " "
13202                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13203                                : a.info.name) + ":");
13204                Log.v(TAG, "    Class=" + a.info.name);
13205            }
13206            final int NI = a.intents.size();
13207            for (int j=0; j<NI; j++) {
13208                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13209                if (DEBUG_SHOW_INFO) {
13210                    Log.v(TAG, "    IntentFilter:");
13211                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13212                }
13213                removeFilter(intent);
13214            }
13215        }
13216
13217        @Override
13218        protected boolean allowFilterResult(
13219                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13220            ActivityInfo filterAi = filter.activity.info;
13221            for (int i=dest.size()-1; i>=0; i--) {
13222                ActivityInfo destAi = dest.get(i).activityInfo;
13223                if (destAi.name == filterAi.name
13224                        && destAi.packageName == filterAi.packageName) {
13225                    return false;
13226                }
13227            }
13228            return true;
13229        }
13230
13231        @Override
13232        protected ActivityIntentInfo[] newArray(int size) {
13233            return new ActivityIntentInfo[size];
13234        }
13235
13236        @Override
13237        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13238            if (!sUserManager.exists(userId)) return true;
13239            PackageParser.Package p = filter.activity.owner;
13240            if (p != null) {
13241                PackageSetting ps = (PackageSetting)p.mExtras;
13242                if (ps != null) {
13243                    // System apps are never considered stopped for purposes of
13244                    // filtering, because there may be no way for the user to
13245                    // actually re-launch them.
13246                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13247                            && ps.getStopped(userId);
13248                }
13249            }
13250            return false;
13251        }
13252
13253        @Override
13254        protected boolean isPackageForFilter(String packageName,
13255                PackageParser.ActivityIntentInfo info) {
13256            return packageName.equals(info.activity.owner.packageName);
13257        }
13258
13259        @Override
13260        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13261                int match, int userId) {
13262            if (!sUserManager.exists(userId)) return null;
13263            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13264                return null;
13265            }
13266            final PackageParser.Activity activity = info.activity;
13267            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13268            if (ps == null) {
13269                return null;
13270            }
13271            final PackageUserState userState = ps.readUserState(userId);
13272            ActivityInfo ai =
13273                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13274            if (ai == null) {
13275                return null;
13276            }
13277            final boolean matchExplicitlyVisibleOnly =
13278                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13279            final boolean matchVisibleToInstantApp =
13280                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13281            final boolean componentVisible =
13282                    matchVisibleToInstantApp
13283                    && info.isVisibleToInstantApp()
13284                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13285            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13286            // throw out filters that aren't visible to ephemeral apps
13287            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13288                return null;
13289            }
13290            // throw out instant app filters if we're not explicitly requesting them
13291            if (!matchInstantApp && userState.instantApp) {
13292                return null;
13293            }
13294            // throw out instant app filters if updates are available; will trigger
13295            // instant app resolution
13296            if (userState.instantApp && ps.isUpdateAvailable()) {
13297                return null;
13298            }
13299            final ResolveInfo res = new ResolveInfo();
13300            res.activityInfo = ai;
13301            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13302                res.filter = info;
13303            }
13304            if (info != null) {
13305                res.handleAllWebDataURI = info.handleAllWebDataURI();
13306            }
13307            res.priority = info.getPriority();
13308            res.preferredOrder = activity.owner.mPreferredOrder;
13309            //System.out.println("Result: " + res.activityInfo.className +
13310            //                   " = " + res.priority);
13311            res.match = match;
13312            res.isDefault = info.hasDefault;
13313            res.labelRes = info.labelRes;
13314            res.nonLocalizedLabel = info.nonLocalizedLabel;
13315            if (userNeedsBadging(userId)) {
13316                res.noResourceId = true;
13317            } else {
13318                res.icon = info.icon;
13319            }
13320            res.iconResourceId = info.icon;
13321            res.system = res.activityInfo.applicationInfo.isSystemApp();
13322            res.isInstantAppAvailable = userState.instantApp;
13323            return res;
13324        }
13325
13326        @Override
13327        protected void sortResults(List<ResolveInfo> results) {
13328            Collections.sort(results, mResolvePrioritySorter);
13329        }
13330
13331        @Override
13332        protected void dumpFilter(PrintWriter out, String prefix,
13333                PackageParser.ActivityIntentInfo filter) {
13334            out.print(prefix); out.print(
13335                    Integer.toHexString(System.identityHashCode(filter.activity)));
13336                    out.print(' ');
13337                    filter.activity.printComponentShortName(out);
13338                    out.print(" filter ");
13339                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13340        }
13341
13342        @Override
13343        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13344            return filter.activity;
13345        }
13346
13347        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13348            PackageParser.Activity activity = (PackageParser.Activity)label;
13349            out.print(prefix); out.print(
13350                    Integer.toHexString(System.identityHashCode(activity)));
13351                    out.print(' ');
13352                    activity.printComponentShortName(out);
13353            if (count > 1) {
13354                out.print(" ("); out.print(count); out.print(" filters)");
13355            }
13356            out.println();
13357        }
13358
13359        // Keys are String (activity class name), values are Activity.
13360        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13361                = new ArrayMap<ComponentName, PackageParser.Activity>();
13362        private int mFlags;
13363    }
13364
13365    private final class ServiceIntentResolver
13366            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13367        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13368                boolean defaultOnly, int userId) {
13369            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13370            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13371        }
13372
13373        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13374                int userId) {
13375            if (!sUserManager.exists(userId)) return null;
13376            mFlags = flags;
13377            return super.queryIntent(intent, resolvedType,
13378                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13379                    userId);
13380        }
13381
13382        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13383                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13384            if (!sUserManager.exists(userId)) return null;
13385            if (packageServices == null) {
13386                return null;
13387            }
13388            mFlags = flags;
13389            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13390            final int N = packageServices.size();
13391            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13392                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13393
13394            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13395            for (int i = 0; i < N; ++i) {
13396                intentFilters = packageServices.get(i).intents;
13397                if (intentFilters != null && intentFilters.size() > 0) {
13398                    PackageParser.ServiceIntentInfo[] array =
13399                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13400                    intentFilters.toArray(array);
13401                    listCut.add(array);
13402                }
13403            }
13404            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13405        }
13406
13407        public final void addService(PackageParser.Service s) {
13408            mServices.put(s.getComponentName(), s);
13409            if (DEBUG_SHOW_INFO) {
13410                Log.v(TAG, "  "
13411                        + (s.info.nonLocalizedLabel != null
13412                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13413                Log.v(TAG, "    Class=" + s.info.name);
13414            }
13415            final int NI = s.intents.size();
13416            int j;
13417            for (j=0; j<NI; j++) {
13418                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13419                if (DEBUG_SHOW_INFO) {
13420                    Log.v(TAG, "    IntentFilter:");
13421                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13422                }
13423                if (!intent.debugCheck()) {
13424                    Log.w(TAG, "==> For Service " + s.info.name);
13425                }
13426                addFilter(intent);
13427            }
13428        }
13429
13430        public final void removeService(PackageParser.Service s) {
13431            mServices.remove(s.getComponentName());
13432            if (DEBUG_SHOW_INFO) {
13433                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13434                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13435                Log.v(TAG, "    Class=" + s.info.name);
13436            }
13437            final int NI = s.intents.size();
13438            int j;
13439            for (j=0; j<NI; j++) {
13440                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13441                if (DEBUG_SHOW_INFO) {
13442                    Log.v(TAG, "    IntentFilter:");
13443                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13444                }
13445                removeFilter(intent);
13446            }
13447        }
13448
13449        @Override
13450        protected boolean allowFilterResult(
13451                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13452            ServiceInfo filterSi = filter.service.info;
13453            for (int i=dest.size()-1; i>=0; i--) {
13454                ServiceInfo destAi = dest.get(i).serviceInfo;
13455                if (destAi.name == filterSi.name
13456                        && destAi.packageName == filterSi.packageName) {
13457                    return false;
13458                }
13459            }
13460            return true;
13461        }
13462
13463        @Override
13464        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13465            return new PackageParser.ServiceIntentInfo[size];
13466        }
13467
13468        @Override
13469        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13470            if (!sUserManager.exists(userId)) return true;
13471            PackageParser.Package p = filter.service.owner;
13472            if (p != null) {
13473                PackageSetting ps = (PackageSetting)p.mExtras;
13474                if (ps != null) {
13475                    // System apps are never considered stopped for purposes of
13476                    // filtering, because there may be no way for the user to
13477                    // actually re-launch them.
13478                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13479                            && ps.getStopped(userId);
13480                }
13481            }
13482            return false;
13483        }
13484
13485        @Override
13486        protected boolean isPackageForFilter(String packageName,
13487                PackageParser.ServiceIntentInfo info) {
13488            return packageName.equals(info.service.owner.packageName);
13489        }
13490
13491        @Override
13492        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13493                int match, int userId) {
13494            if (!sUserManager.exists(userId)) return null;
13495            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13496            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13497                return null;
13498            }
13499            final PackageParser.Service service = info.service;
13500            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13501            if (ps == null) {
13502                return null;
13503            }
13504            final PackageUserState userState = ps.readUserState(userId);
13505            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13506                    userState, userId);
13507            if (si == null) {
13508                return null;
13509            }
13510            final boolean matchVisibleToInstantApp =
13511                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13512            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13513            // throw out filters that aren't visible to ephemeral apps
13514            if (matchVisibleToInstantApp
13515                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13516                return null;
13517            }
13518            // throw out ephemeral filters if we're not explicitly requesting them
13519            if (!isInstantApp && userState.instantApp) {
13520                return null;
13521            }
13522            // throw out instant app filters if updates are available; will trigger
13523            // instant app resolution
13524            if (userState.instantApp && ps.isUpdateAvailable()) {
13525                return null;
13526            }
13527            final ResolveInfo res = new ResolveInfo();
13528            res.serviceInfo = si;
13529            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13530                res.filter = filter;
13531            }
13532            res.priority = info.getPriority();
13533            res.preferredOrder = service.owner.mPreferredOrder;
13534            res.match = match;
13535            res.isDefault = info.hasDefault;
13536            res.labelRes = info.labelRes;
13537            res.nonLocalizedLabel = info.nonLocalizedLabel;
13538            res.icon = info.icon;
13539            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13540            return res;
13541        }
13542
13543        @Override
13544        protected void sortResults(List<ResolveInfo> results) {
13545            Collections.sort(results, mResolvePrioritySorter);
13546        }
13547
13548        @Override
13549        protected void dumpFilter(PrintWriter out, String prefix,
13550                PackageParser.ServiceIntentInfo filter) {
13551            out.print(prefix); out.print(
13552                    Integer.toHexString(System.identityHashCode(filter.service)));
13553                    out.print(' ');
13554                    filter.service.printComponentShortName(out);
13555                    out.print(" filter ");
13556                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13557        }
13558
13559        @Override
13560        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13561            return filter.service;
13562        }
13563
13564        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13565            PackageParser.Service service = (PackageParser.Service)label;
13566            out.print(prefix); out.print(
13567                    Integer.toHexString(System.identityHashCode(service)));
13568                    out.print(' ');
13569                    service.printComponentShortName(out);
13570            if (count > 1) {
13571                out.print(" ("); out.print(count); out.print(" filters)");
13572            }
13573            out.println();
13574        }
13575
13576//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13577//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13578//            final List<ResolveInfo> retList = Lists.newArrayList();
13579//            while (i.hasNext()) {
13580//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13581//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13582//                    retList.add(resolveInfo);
13583//                }
13584//            }
13585//            return retList;
13586//        }
13587
13588        // Keys are String (activity class name), values are Activity.
13589        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13590                = new ArrayMap<ComponentName, PackageParser.Service>();
13591        private int mFlags;
13592    }
13593
13594    private final class ProviderIntentResolver
13595            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13596        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13597                boolean defaultOnly, int userId) {
13598            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13599            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13600        }
13601
13602        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13603                int userId) {
13604            if (!sUserManager.exists(userId))
13605                return null;
13606            mFlags = flags;
13607            return super.queryIntent(intent, resolvedType,
13608                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13609                    userId);
13610        }
13611
13612        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13613                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13614            if (!sUserManager.exists(userId))
13615                return null;
13616            if (packageProviders == null) {
13617                return null;
13618            }
13619            mFlags = flags;
13620            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13621            final int N = packageProviders.size();
13622            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13623                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13624
13625            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13626            for (int i = 0; i < N; ++i) {
13627                intentFilters = packageProviders.get(i).intents;
13628                if (intentFilters != null && intentFilters.size() > 0) {
13629                    PackageParser.ProviderIntentInfo[] array =
13630                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13631                    intentFilters.toArray(array);
13632                    listCut.add(array);
13633                }
13634            }
13635            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13636        }
13637
13638        public final void addProvider(PackageParser.Provider p) {
13639            if (mProviders.containsKey(p.getComponentName())) {
13640                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13641                return;
13642            }
13643
13644            mProviders.put(p.getComponentName(), p);
13645            if (DEBUG_SHOW_INFO) {
13646                Log.v(TAG, "  "
13647                        + (p.info.nonLocalizedLabel != null
13648                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13649                Log.v(TAG, "    Class=" + p.info.name);
13650            }
13651            final int NI = p.intents.size();
13652            int j;
13653            for (j = 0; j < NI; j++) {
13654                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13655                if (DEBUG_SHOW_INFO) {
13656                    Log.v(TAG, "    IntentFilter:");
13657                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13658                }
13659                if (!intent.debugCheck()) {
13660                    Log.w(TAG, "==> For Provider " + p.info.name);
13661                }
13662                addFilter(intent);
13663            }
13664        }
13665
13666        public final void removeProvider(PackageParser.Provider p) {
13667            mProviders.remove(p.getComponentName());
13668            if (DEBUG_SHOW_INFO) {
13669                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13670                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13671                Log.v(TAG, "    Class=" + p.info.name);
13672            }
13673            final int NI = p.intents.size();
13674            int j;
13675            for (j = 0; j < NI; j++) {
13676                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13677                if (DEBUG_SHOW_INFO) {
13678                    Log.v(TAG, "    IntentFilter:");
13679                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13680                }
13681                removeFilter(intent);
13682            }
13683        }
13684
13685        @Override
13686        protected boolean allowFilterResult(
13687                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13688            ProviderInfo filterPi = filter.provider.info;
13689            for (int i = dest.size() - 1; i >= 0; i--) {
13690                ProviderInfo destPi = dest.get(i).providerInfo;
13691                if (destPi.name == filterPi.name
13692                        && destPi.packageName == filterPi.packageName) {
13693                    return false;
13694                }
13695            }
13696            return true;
13697        }
13698
13699        @Override
13700        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13701            return new PackageParser.ProviderIntentInfo[size];
13702        }
13703
13704        @Override
13705        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13706            if (!sUserManager.exists(userId))
13707                return true;
13708            PackageParser.Package p = filter.provider.owner;
13709            if (p != null) {
13710                PackageSetting ps = (PackageSetting) p.mExtras;
13711                if (ps != null) {
13712                    // System apps are never considered stopped for purposes of
13713                    // filtering, because there may be no way for the user to
13714                    // actually re-launch them.
13715                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13716                            && ps.getStopped(userId);
13717                }
13718            }
13719            return false;
13720        }
13721
13722        @Override
13723        protected boolean isPackageForFilter(String packageName,
13724                PackageParser.ProviderIntentInfo info) {
13725            return packageName.equals(info.provider.owner.packageName);
13726        }
13727
13728        @Override
13729        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13730                int match, int userId) {
13731            if (!sUserManager.exists(userId))
13732                return null;
13733            final PackageParser.ProviderIntentInfo info = filter;
13734            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13735                return null;
13736            }
13737            final PackageParser.Provider provider = info.provider;
13738            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13739            if (ps == null) {
13740                return null;
13741            }
13742            final PackageUserState userState = ps.readUserState(userId);
13743            final boolean matchVisibleToInstantApp =
13744                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13745            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13746            // throw out filters that aren't visible to instant applications
13747            if (matchVisibleToInstantApp
13748                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13749                return null;
13750            }
13751            // throw out instant application filters if we're not explicitly requesting them
13752            if (!isInstantApp && userState.instantApp) {
13753                return null;
13754            }
13755            // throw out instant application filters if updates are available; will trigger
13756            // instant application resolution
13757            if (userState.instantApp && ps.isUpdateAvailable()) {
13758                return null;
13759            }
13760            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13761                    userState, userId);
13762            if (pi == null) {
13763                return null;
13764            }
13765            final ResolveInfo res = new ResolveInfo();
13766            res.providerInfo = pi;
13767            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13768                res.filter = filter;
13769            }
13770            res.priority = info.getPriority();
13771            res.preferredOrder = provider.owner.mPreferredOrder;
13772            res.match = match;
13773            res.isDefault = info.hasDefault;
13774            res.labelRes = info.labelRes;
13775            res.nonLocalizedLabel = info.nonLocalizedLabel;
13776            res.icon = info.icon;
13777            res.system = res.providerInfo.applicationInfo.isSystemApp();
13778            return res;
13779        }
13780
13781        @Override
13782        protected void sortResults(List<ResolveInfo> results) {
13783            Collections.sort(results, mResolvePrioritySorter);
13784        }
13785
13786        @Override
13787        protected void dumpFilter(PrintWriter out, String prefix,
13788                PackageParser.ProviderIntentInfo filter) {
13789            out.print(prefix);
13790            out.print(
13791                    Integer.toHexString(System.identityHashCode(filter.provider)));
13792            out.print(' ');
13793            filter.provider.printComponentShortName(out);
13794            out.print(" filter ");
13795            out.println(Integer.toHexString(System.identityHashCode(filter)));
13796        }
13797
13798        @Override
13799        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13800            return filter.provider;
13801        }
13802
13803        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13804            PackageParser.Provider provider = (PackageParser.Provider)label;
13805            out.print(prefix); out.print(
13806                    Integer.toHexString(System.identityHashCode(provider)));
13807                    out.print(' ');
13808                    provider.printComponentShortName(out);
13809            if (count > 1) {
13810                out.print(" ("); out.print(count); out.print(" filters)");
13811            }
13812            out.println();
13813        }
13814
13815        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13816                = new ArrayMap<ComponentName, PackageParser.Provider>();
13817        private int mFlags;
13818    }
13819
13820    static final class EphemeralIntentResolver
13821            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13822        /**
13823         * The result that has the highest defined order. Ordering applies on a
13824         * per-package basis. Mapping is from package name to Pair of order and
13825         * EphemeralResolveInfo.
13826         * <p>
13827         * NOTE: This is implemented as a field variable for convenience and efficiency.
13828         * By having a field variable, we're able to track filter ordering as soon as
13829         * a non-zero order is defined. Otherwise, multiple loops across the result set
13830         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13831         * this needs to be contained entirely within {@link #filterResults}.
13832         */
13833        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13834
13835        @Override
13836        protected AuxiliaryResolveInfo[] newArray(int size) {
13837            return new AuxiliaryResolveInfo[size];
13838        }
13839
13840        @Override
13841        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13842            return true;
13843        }
13844
13845        @Override
13846        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13847                int userId) {
13848            if (!sUserManager.exists(userId)) {
13849                return null;
13850            }
13851            final String packageName = responseObj.resolveInfo.getPackageName();
13852            final Integer order = responseObj.getOrder();
13853            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13854                    mOrderResult.get(packageName);
13855            // ordering is enabled and this item's order isn't high enough
13856            if (lastOrderResult != null && lastOrderResult.first >= order) {
13857                return null;
13858            }
13859            final InstantAppResolveInfo res = responseObj.resolveInfo;
13860            if (order > 0) {
13861                // non-zero order, enable ordering
13862                mOrderResult.put(packageName, new Pair<>(order, res));
13863            }
13864            return responseObj;
13865        }
13866
13867        @Override
13868        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13869            // only do work if ordering is enabled [most of the time it won't be]
13870            if (mOrderResult.size() == 0) {
13871                return;
13872            }
13873            int resultSize = results.size();
13874            for (int i = 0; i < resultSize; i++) {
13875                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13876                final String packageName = info.getPackageName();
13877                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13878                if (savedInfo == null) {
13879                    // package doesn't having ordering
13880                    continue;
13881                }
13882                if (savedInfo.second == info) {
13883                    // circled back to the highest ordered item; remove from order list
13884                    mOrderResult.remove(savedInfo);
13885                    if (mOrderResult.size() == 0) {
13886                        // no more ordered items
13887                        break;
13888                    }
13889                    continue;
13890                }
13891                // item has a worse order, remove it from the result list
13892                results.remove(i);
13893                resultSize--;
13894                i--;
13895            }
13896        }
13897    }
13898
13899    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13900            new Comparator<ResolveInfo>() {
13901        public int compare(ResolveInfo r1, ResolveInfo r2) {
13902            int v1 = r1.priority;
13903            int v2 = r2.priority;
13904            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13905            if (v1 != v2) {
13906                return (v1 > v2) ? -1 : 1;
13907            }
13908            v1 = r1.preferredOrder;
13909            v2 = r2.preferredOrder;
13910            if (v1 != v2) {
13911                return (v1 > v2) ? -1 : 1;
13912            }
13913            if (r1.isDefault != r2.isDefault) {
13914                return r1.isDefault ? -1 : 1;
13915            }
13916            v1 = r1.match;
13917            v2 = r2.match;
13918            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13919            if (v1 != v2) {
13920                return (v1 > v2) ? -1 : 1;
13921            }
13922            if (r1.system != r2.system) {
13923                return r1.system ? -1 : 1;
13924            }
13925            if (r1.activityInfo != null) {
13926                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13927            }
13928            if (r1.serviceInfo != null) {
13929                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13930            }
13931            if (r1.providerInfo != null) {
13932                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13933            }
13934            return 0;
13935        }
13936    };
13937
13938    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13939            new Comparator<ProviderInfo>() {
13940        public int compare(ProviderInfo p1, ProviderInfo p2) {
13941            final int v1 = p1.initOrder;
13942            final int v2 = p2.initOrder;
13943            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13944        }
13945    };
13946
13947    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13948            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13949            final int[] userIds) {
13950        mHandler.post(new Runnable() {
13951            @Override
13952            public void run() {
13953                try {
13954                    final IActivityManager am = ActivityManager.getService();
13955                    if (am == null) return;
13956                    final int[] resolvedUserIds;
13957                    if (userIds == null) {
13958                        resolvedUserIds = am.getRunningUserIds();
13959                    } else {
13960                        resolvedUserIds = userIds;
13961                    }
13962                    for (int id : resolvedUserIds) {
13963                        final Intent intent = new Intent(action,
13964                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13965                        if (extras != null) {
13966                            intent.putExtras(extras);
13967                        }
13968                        if (targetPkg != null) {
13969                            intent.setPackage(targetPkg);
13970                        }
13971                        // Modify the UID when posting to other users
13972                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13973                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13974                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13975                            intent.putExtra(Intent.EXTRA_UID, uid);
13976                        }
13977                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13978                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13979                        if (DEBUG_BROADCASTS) {
13980                            RuntimeException here = new RuntimeException("here");
13981                            here.fillInStackTrace();
13982                            Slog.d(TAG, "Sending to user " + id + ": "
13983                                    + intent.toShortString(false, true, false, false)
13984                                    + " " + intent.getExtras(), here);
13985                        }
13986                        am.broadcastIntent(null, intent, null, finishedReceiver,
13987                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13988                                null, finishedReceiver != null, false, id);
13989                    }
13990                } catch (RemoteException ex) {
13991                }
13992            }
13993        });
13994    }
13995
13996    /**
13997     * Check if the external storage media is available. This is true if there
13998     * is a mounted external storage medium or if the external storage is
13999     * emulated.
14000     */
14001    private boolean isExternalMediaAvailable() {
14002        return mMediaMounted || Environment.isExternalStorageEmulated();
14003    }
14004
14005    @Override
14006    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14007        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14008            return null;
14009        }
14010        // writer
14011        synchronized (mPackages) {
14012            if (!isExternalMediaAvailable()) {
14013                // If the external storage is no longer mounted at this point,
14014                // the caller may not have been able to delete all of this
14015                // packages files and can not delete any more.  Bail.
14016                return null;
14017            }
14018            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14019            if (lastPackage != null) {
14020                pkgs.remove(lastPackage);
14021            }
14022            if (pkgs.size() > 0) {
14023                return pkgs.get(0);
14024            }
14025        }
14026        return null;
14027    }
14028
14029    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14030        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14031                userId, andCode ? 1 : 0, packageName);
14032        if (mSystemReady) {
14033            msg.sendToTarget();
14034        } else {
14035            if (mPostSystemReadyMessages == null) {
14036                mPostSystemReadyMessages = new ArrayList<>();
14037            }
14038            mPostSystemReadyMessages.add(msg);
14039        }
14040    }
14041
14042    void startCleaningPackages() {
14043        // reader
14044        if (!isExternalMediaAvailable()) {
14045            return;
14046        }
14047        synchronized (mPackages) {
14048            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14049                return;
14050            }
14051        }
14052        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14053        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14054        IActivityManager am = ActivityManager.getService();
14055        if (am != null) {
14056            int dcsUid = -1;
14057            synchronized (mPackages) {
14058                if (!mDefaultContainerWhitelisted) {
14059                    mDefaultContainerWhitelisted = true;
14060                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14061                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14062                }
14063            }
14064            try {
14065                if (dcsUid > 0) {
14066                    am.backgroundWhitelistUid(dcsUid);
14067                }
14068                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14069                        UserHandle.USER_SYSTEM);
14070            } catch (RemoteException e) {
14071            }
14072        }
14073    }
14074
14075    @Override
14076    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14077            int installFlags, String installerPackageName, int userId) {
14078        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14079
14080        final int callingUid = Binder.getCallingUid();
14081        enforceCrossUserPermission(callingUid, userId,
14082                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14083
14084        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14085            try {
14086                if (observer != null) {
14087                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14088                }
14089            } catch (RemoteException re) {
14090            }
14091            return;
14092        }
14093
14094        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14095            installFlags |= PackageManager.INSTALL_FROM_ADB;
14096
14097        } else {
14098            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14099            // about installerPackageName.
14100
14101            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14102            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14103        }
14104
14105        UserHandle user;
14106        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14107            user = UserHandle.ALL;
14108        } else {
14109            user = new UserHandle(userId);
14110        }
14111
14112        // Only system components can circumvent runtime permissions when installing.
14113        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14114                && mContext.checkCallingOrSelfPermission(Manifest.permission
14115                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14116            throw new SecurityException("You need the "
14117                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14118                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14119        }
14120
14121        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14122                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14123            throw new IllegalArgumentException(
14124                    "New installs into ASEC containers no longer supported");
14125        }
14126
14127        final File originFile = new File(originPath);
14128        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14129
14130        final Message msg = mHandler.obtainMessage(INIT_COPY);
14131        final VerificationInfo verificationInfo = new VerificationInfo(
14132                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14133        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14134                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14135                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14136                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14137        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14138        msg.obj = params;
14139
14140        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14141                System.identityHashCode(msg.obj));
14142        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14143                System.identityHashCode(msg.obj));
14144
14145        mHandler.sendMessage(msg);
14146    }
14147
14148
14149    /**
14150     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14151     * it is acting on behalf on an enterprise or the user).
14152     *
14153     * Note that the ordering of the conditionals in this method is important. The checks we perform
14154     * are as follows, in this order:
14155     *
14156     * 1) If the install is being performed by a system app, we can trust the app to have set the
14157     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14158     *    what it is.
14159     * 2) If the install is being performed by a device or profile owner app, the install reason
14160     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14161     *    set the install reason correctly. If the app targets an older SDK version where install
14162     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14163     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14164     * 3) In all other cases, the install is being performed by a regular app that is neither part
14165     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14166     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14167     *    set to enterprise policy and if so, change it to unknown instead.
14168     */
14169    private int fixUpInstallReason(String installerPackageName, int installerUid,
14170            int installReason) {
14171        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14172                == PERMISSION_GRANTED) {
14173            // If the install is being performed by a system app, we trust that app to have set the
14174            // install reason correctly.
14175            return installReason;
14176        }
14177
14178        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14179            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14180        if (dpm != null) {
14181            ComponentName owner = null;
14182            try {
14183                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14184                if (owner == null) {
14185                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14186                }
14187            } catch (RemoteException e) {
14188            }
14189            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14190                // If the install is being performed by a device or profile owner, the install
14191                // reason should be enterprise policy.
14192                return PackageManager.INSTALL_REASON_POLICY;
14193            }
14194        }
14195
14196        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14197            // If the install is being performed by a regular app (i.e. neither system app nor
14198            // device or profile owner), we have no reason to believe that the app is acting on
14199            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14200            // change it to unknown instead.
14201            return PackageManager.INSTALL_REASON_UNKNOWN;
14202        }
14203
14204        // If the install is being performed by a regular app and the install reason was set to any
14205        // value but enterprise policy, leave the install reason unchanged.
14206        return installReason;
14207    }
14208
14209    void installStage(String packageName, File stagedDir, String stagedCid,
14210            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14211            String installerPackageName, int installerUid, UserHandle user,
14212            Certificate[][] certificates) {
14213        if (DEBUG_EPHEMERAL) {
14214            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14215                Slog.d(TAG, "Ephemeral install of " + packageName);
14216            }
14217        }
14218        final VerificationInfo verificationInfo = new VerificationInfo(
14219                sessionParams.originatingUri, sessionParams.referrerUri,
14220                sessionParams.originatingUid, installerUid);
14221
14222        final OriginInfo origin;
14223        if (stagedDir != null) {
14224            origin = OriginInfo.fromStagedFile(stagedDir);
14225        } else {
14226            origin = OriginInfo.fromStagedContainer(stagedCid);
14227        }
14228
14229        final Message msg = mHandler.obtainMessage(INIT_COPY);
14230        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14231                sessionParams.installReason);
14232        final InstallParams params = new InstallParams(origin, null, observer,
14233                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14234                verificationInfo, user, sessionParams.abiOverride,
14235                sessionParams.grantedRuntimePermissions, certificates, installReason);
14236        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14237        msg.obj = params;
14238
14239        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14240                System.identityHashCode(msg.obj));
14241        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14242                System.identityHashCode(msg.obj));
14243
14244        mHandler.sendMessage(msg);
14245    }
14246
14247    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14248            int userId) {
14249        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14250        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14251
14252        // Send a session commit broadcast
14253        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14254        info.installReason = pkgSetting.getInstallReason(userId);
14255        info.appPackageName = packageName;
14256        sendSessionCommitBroadcast(info, userId);
14257    }
14258
14259    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14260        if (ArrayUtils.isEmpty(userIds)) {
14261            return;
14262        }
14263        Bundle extras = new Bundle(1);
14264        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14265        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14266
14267        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14268                packageName, extras, 0, null, null, userIds);
14269        if (isSystem) {
14270            mHandler.post(() -> {
14271                        for (int userId : userIds) {
14272                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14273                        }
14274                    }
14275            );
14276        }
14277    }
14278
14279    /**
14280     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14281     * automatically without needing an explicit launch.
14282     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14283     */
14284    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14285        // If user is not running, the app didn't miss any broadcast
14286        if (!mUserManagerInternal.isUserRunning(userId)) {
14287            return;
14288        }
14289        final IActivityManager am = ActivityManager.getService();
14290        try {
14291            // Deliver LOCKED_BOOT_COMPLETED first
14292            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14293                    .setPackage(packageName);
14294            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14295            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14296                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14297
14298            // Deliver BOOT_COMPLETED only if user is unlocked
14299            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14300                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14301                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14302                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14303            }
14304        } catch (RemoteException e) {
14305            throw e.rethrowFromSystemServer();
14306        }
14307    }
14308
14309    @Override
14310    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14311            int userId) {
14312        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14313        PackageSetting pkgSetting;
14314        final int callingUid = Binder.getCallingUid();
14315        enforceCrossUserPermission(callingUid, userId,
14316                true /* requireFullPermission */, true /* checkShell */,
14317                "setApplicationHiddenSetting for user " + userId);
14318
14319        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14320            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14321            return false;
14322        }
14323
14324        long callingId = Binder.clearCallingIdentity();
14325        try {
14326            boolean sendAdded = false;
14327            boolean sendRemoved = false;
14328            // writer
14329            synchronized (mPackages) {
14330                pkgSetting = mSettings.mPackages.get(packageName);
14331                if (pkgSetting == null) {
14332                    return false;
14333                }
14334                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14335                    return false;
14336                }
14337                // Do not allow "android" is being disabled
14338                if ("android".equals(packageName)) {
14339                    Slog.w(TAG, "Cannot hide package: android");
14340                    return false;
14341                }
14342                // Cannot hide static shared libs as they are considered
14343                // a part of the using app (emulating static linking). Also
14344                // static libs are installed always on internal storage.
14345                PackageParser.Package pkg = mPackages.get(packageName);
14346                if (pkg != null && pkg.staticSharedLibName != null) {
14347                    Slog.w(TAG, "Cannot hide package: " + packageName
14348                            + " providing static shared library: "
14349                            + pkg.staticSharedLibName);
14350                    return false;
14351                }
14352                // Only allow protected packages to hide themselves.
14353                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14354                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14355                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14356                    return false;
14357                }
14358
14359                if (pkgSetting.getHidden(userId) != hidden) {
14360                    pkgSetting.setHidden(hidden, userId);
14361                    mSettings.writePackageRestrictionsLPr(userId);
14362                    if (hidden) {
14363                        sendRemoved = true;
14364                    } else {
14365                        sendAdded = true;
14366                    }
14367                }
14368            }
14369            if (sendAdded) {
14370                sendPackageAddedForUser(packageName, pkgSetting, userId);
14371                return true;
14372            }
14373            if (sendRemoved) {
14374                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14375                        "hiding pkg");
14376                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14377                return true;
14378            }
14379        } finally {
14380            Binder.restoreCallingIdentity(callingId);
14381        }
14382        return false;
14383    }
14384
14385    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14386            int userId) {
14387        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14388        info.removedPackage = packageName;
14389        info.installerPackageName = pkgSetting.installerPackageName;
14390        info.removedUsers = new int[] {userId};
14391        info.broadcastUsers = new int[] {userId};
14392        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14393        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14394    }
14395
14396    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14397        if (pkgList.length > 0) {
14398            Bundle extras = new Bundle(1);
14399            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14400
14401            sendPackageBroadcast(
14402                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14403                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14404                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14405                    new int[] {userId});
14406        }
14407    }
14408
14409    /**
14410     * Returns true if application is not found or there was an error. Otherwise it returns
14411     * the hidden state of the package for the given user.
14412     */
14413    @Override
14414    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14415        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14416        final int callingUid = Binder.getCallingUid();
14417        enforceCrossUserPermission(callingUid, userId,
14418                true /* requireFullPermission */, false /* checkShell */,
14419                "getApplicationHidden for user " + userId);
14420        PackageSetting ps;
14421        long callingId = Binder.clearCallingIdentity();
14422        try {
14423            // writer
14424            synchronized (mPackages) {
14425                ps = mSettings.mPackages.get(packageName);
14426                if (ps == null) {
14427                    return true;
14428                }
14429                if (filterAppAccessLPr(ps, callingUid, userId)) {
14430                    return true;
14431                }
14432                return ps.getHidden(userId);
14433            }
14434        } finally {
14435            Binder.restoreCallingIdentity(callingId);
14436        }
14437    }
14438
14439    /**
14440     * @hide
14441     */
14442    @Override
14443    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14444            int installReason) {
14445        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14446                null);
14447        PackageSetting pkgSetting;
14448        final int callingUid = Binder.getCallingUid();
14449        enforceCrossUserPermission(callingUid, userId,
14450                true /* requireFullPermission */, true /* checkShell */,
14451                "installExistingPackage for user " + userId);
14452        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14453            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14454        }
14455
14456        long callingId = Binder.clearCallingIdentity();
14457        try {
14458            boolean installed = false;
14459            final boolean instantApp =
14460                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14461            final boolean fullApp =
14462                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14463
14464            // writer
14465            synchronized (mPackages) {
14466                pkgSetting = mSettings.mPackages.get(packageName);
14467                if (pkgSetting == null) {
14468                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14469                }
14470                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14471                    // only allow the existing package to be used if it's installed as a full
14472                    // application for at least one user
14473                    boolean installAllowed = false;
14474                    for (int checkUserId : sUserManager.getUserIds()) {
14475                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14476                        if (installAllowed) {
14477                            break;
14478                        }
14479                    }
14480                    if (!installAllowed) {
14481                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14482                    }
14483                }
14484                if (!pkgSetting.getInstalled(userId)) {
14485                    pkgSetting.setInstalled(true, userId);
14486                    pkgSetting.setHidden(false, userId);
14487                    pkgSetting.setInstallReason(installReason, userId);
14488                    mSettings.writePackageRestrictionsLPr(userId);
14489                    mSettings.writeKernelMappingLPr(pkgSetting);
14490                    installed = true;
14491                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14492                    // upgrade app from instant to full; we don't allow app downgrade
14493                    installed = true;
14494                }
14495                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14496            }
14497
14498            if (installed) {
14499                if (pkgSetting.pkg != null) {
14500                    synchronized (mInstallLock) {
14501                        // We don't need to freeze for a brand new install
14502                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14503                    }
14504                }
14505                sendPackageAddedForUser(packageName, pkgSetting, userId);
14506                synchronized (mPackages) {
14507                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14508                }
14509            }
14510        } finally {
14511            Binder.restoreCallingIdentity(callingId);
14512        }
14513
14514        return PackageManager.INSTALL_SUCCEEDED;
14515    }
14516
14517    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14518            boolean instantApp, boolean fullApp) {
14519        // no state specified; do nothing
14520        if (!instantApp && !fullApp) {
14521            return;
14522        }
14523        if (userId != UserHandle.USER_ALL) {
14524            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14525                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14526            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14527                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14528            }
14529        } else {
14530            for (int currentUserId : sUserManager.getUserIds()) {
14531                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14532                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14533                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14534                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14535                }
14536            }
14537        }
14538    }
14539
14540    boolean isUserRestricted(int userId, String restrictionKey) {
14541        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14542        if (restrictions.getBoolean(restrictionKey, false)) {
14543            Log.w(TAG, "User is restricted: " + restrictionKey);
14544            return true;
14545        }
14546        return false;
14547    }
14548
14549    @Override
14550    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14551            int userId) {
14552        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14553        final int callingUid = Binder.getCallingUid();
14554        enforceCrossUserPermission(callingUid, userId,
14555                true /* requireFullPermission */, true /* checkShell */,
14556                "setPackagesSuspended for user " + userId);
14557
14558        if (ArrayUtils.isEmpty(packageNames)) {
14559            return packageNames;
14560        }
14561
14562        // List of package names for whom the suspended state has changed.
14563        List<String> changedPackages = new ArrayList<>(packageNames.length);
14564        // List of package names for whom the suspended state is not set as requested in this
14565        // method.
14566        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14567        long callingId = Binder.clearCallingIdentity();
14568        try {
14569            for (int i = 0; i < packageNames.length; i++) {
14570                String packageName = packageNames[i];
14571                boolean changed = false;
14572                final int appId;
14573                synchronized (mPackages) {
14574                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14575                    if (pkgSetting == null
14576                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14577                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14578                                + "\". Skipping suspending/un-suspending.");
14579                        unactionedPackages.add(packageName);
14580                        continue;
14581                    }
14582                    appId = pkgSetting.appId;
14583                    if (pkgSetting.getSuspended(userId) != suspended) {
14584                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14585                            unactionedPackages.add(packageName);
14586                            continue;
14587                        }
14588                        pkgSetting.setSuspended(suspended, userId);
14589                        mSettings.writePackageRestrictionsLPr(userId);
14590                        changed = true;
14591                        changedPackages.add(packageName);
14592                    }
14593                }
14594
14595                if (changed && suspended) {
14596                    killApplication(packageName, UserHandle.getUid(userId, appId),
14597                            "suspending package");
14598                }
14599            }
14600        } finally {
14601            Binder.restoreCallingIdentity(callingId);
14602        }
14603
14604        if (!changedPackages.isEmpty()) {
14605            sendPackagesSuspendedForUser(changedPackages.toArray(
14606                    new String[changedPackages.size()]), userId, suspended);
14607        }
14608
14609        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14610    }
14611
14612    @Override
14613    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14614        final int callingUid = Binder.getCallingUid();
14615        enforceCrossUserPermission(callingUid, userId,
14616                true /* requireFullPermission */, false /* checkShell */,
14617                "isPackageSuspendedForUser for user " + userId);
14618        synchronized (mPackages) {
14619            final PackageSetting ps = mSettings.mPackages.get(packageName);
14620            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14621                throw new IllegalArgumentException("Unknown target package: " + packageName);
14622            }
14623            return ps.getSuspended(userId);
14624        }
14625    }
14626
14627    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14628        if (isPackageDeviceAdmin(packageName, userId)) {
14629            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14630                    + "\": has an active device admin");
14631            return false;
14632        }
14633
14634        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14635        if (packageName.equals(activeLauncherPackageName)) {
14636            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14637                    + "\": contains the active launcher");
14638            return false;
14639        }
14640
14641        if (packageName.equals(mRequiredInstallerPackage)) {
14642            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14643                    + "\": required for package installation");
14644            return false;
14645        }
14646
14647        if (packageName.equals(mRequiredUninstallerPackage)) {
14648            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14649                    + "\": required for package uninstallation");
14650            return false;
14651        }
14652
14653        if (packageName.equals(mRequiredVerifierPackage)) {
14654            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14655                    + "\": required for package verification");
14656            return false;
14657        }
14658
14659        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14660            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14661                    + "\": is the default dialer");
14662            return false;
14663        }
14664
14665        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14666            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14667                    + "\": protected package");
14668            return false;
14669        }
14670
14671        // Cannot suspend static shared libs as they are considered
14672        // a part of the using app (emulating static linking). Also
14673        // static libs are installed always on internal storage.
14674        PackageParser.Package pkg = mPackages.get(packageName);
14675        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14676            Slog.w(TAG, "Cannot suspend package: " + packageName
14677                    + " providing static shared library: "
14678                    + pkg.staticSharedLibName);
14679            return false;
14680        }
14681
14682        return true;
14683    }
14684
14685    private String getActiveLauncherPackageName(int userId) {
14686        Intent intent = new Intent(Intent.ACTION_MAIN);
14687        intent.addCategory(Intent.CATEGORY_HOME);
14688        ResolveInfo resolveInfo = resolveIntent(
14689                intent,
14690                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14691                PackageManager.MATCH_DEFAULT_ONLY,
14692                userId);
14693
14694        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14695    }
14696
14697    private String getDefaultDialerPackageName(int userId) {
14698        synchronized (mPackages) {
14699            return mSettings.getDefaultDialerPackageNameLPw(userId);
14700        }
14701    }
14702
14703    @Override
14704    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14705        mContext.enforceCallingOrSelfPermission(
14706                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14707                "Only package verification agents can verify applications");
14708
14709        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14710        final PackageVerificationResponse response = new PackageVerificationResponse(
14711                verificationCode, Binder.getCallingUid());
14712        msg.arg1 = id;
14713        msg.obj = response;
14714        mHandler.sendMessage(msg);
14715    }
14716
14717    @Override
14718    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14719            long millisecondsToDelay) {
14720        mContext.enforceCallingOrSelfPermission(
14721                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14722                "Only package verification agents can extend verification timeouts");
14723
14724        final PackageVerificationState state = mPendingVerification.get(id);
14725        final PackageVerificationResponse response = new PackageVerificationResponse(
14726                verificationCodeAtTimeout, Binder.getCallingUid());
14727
14728        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14729            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14730        }
14731        if (millisecondsToDelay < 0) {
14732            millisecondsToDelay = 0;
14733        }
14734        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14735                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14736            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14737        }
14738
14739        if ((state != null) && !state.timeoutExtended()) {
14740            state.extendTimeout();
14741
14742            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14743            msg.arg1 = id;
14744            msg.obj = response;
14745            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14746        }
14747    }
14748
14749    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14750            int verificationCode, UserHandle user) {
14751        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14752        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14753        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14754        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14755        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14756
14757        mContext.sendBroadcastAsUser(intent, user,
14758                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14759    }
14760
14761    private ComponentName matchComponentForVerifier(String packageName,
14762            List<ResolveInfo> receivers) {
14763        ActivityInfo targetReceiver = null;
14764
14765        final int NR = receivers.size();
14766        for (int i = 0; i < NR; i++) {
14767            final ResolveInfo info = receivers.get(i);
14768            if (info.activityInfo == null) {
14769                continue;
14770            }
14771
14772            if (packageName.equals(info.activityInfo.packageName)) {
14773                targetReceiver = info.activityInfo;
14774                break;
14775            }
14776        }
14777
14778        if (targetReceiver == null) {
14779            return null;
14780        }
14781
14782        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14783    }
14784
14785    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14786            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14787        if (pkgInfo.verifiers.length == 0) {
14788            return null;
14789        }
14790
14791        final int N = pkgInfo.verifiers.length;
14792        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14793        for (int i = 0; i < N; i++) {
14794            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14795
14796            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14797                    receivers);
14798            if (comp == null) {
14799                continue;
14800            }
14801
14802            final int verifierUid = getUidForVerifier(verifierInfo);
14803            if (verifierUid == -1) {
14804                continue;
14805            }
14806
14807            if (DEBUG_VERIFY) {
14808                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14809                        + " with the correct signature");
14810            }
14811            sufficientVerifiers.add(comp);
14812            verificationState.addSufficientVerifier(verifierUid);
14813        }
14814
14815        return sufficientVerifiers;
14816    }
14817
14818    private int getUidForVerifier(VerifierInfo verifierInfo) {
14819        synchronized (mPackages) {
14820            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14821            if (pkg == null) {
14822                return -1;
14823            } else if (pkg.mSignatures.length != 1) {
14824                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14825                        + " has more than one signature; ignoring");
14826                return -1;
14827            }
14828
14829            /*
14830             * If the public key of the package's signature does not match
14831             * our expected public key, then this is a different package and
14832             * we should skip.
14833             */
14834
14835            final byte[] expectedPublicKey;
14836            try {
14837                final Signature verifierSig = pkg.mSignatures[0];
14838                final PublicKey publicKey = verifierSig.getPublicKey();
14839                expectedPublicKey = publicKey.getEncoded();
14840            } catch (CertificateException e) {
14841                return -1;
14842            }
14843
14844            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14845
14846            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14847                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14848                        + " does not have the expected public key; ignoring");
14849                return -1;
14850            }
14851
14852            return pkg.applicationInfo.uid;
14853        }
14854    }
14855
14856    @Override
14857    public void finishPackageInstall(int token, boolean didLaunch) {
14858        enforceSystemOrRoot("Only the system is allowed to finish installs");
14859
14860        if (DEBUG_INSTALL) {
14861            Slog.v(TAG, "BM finishing package install for " + token);
14862        }
14863        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14864
14865        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14866        mHandler.sendMessage(msg);
14867    }
14868
14869    /**
14870     * Get the verification agent timeout.  Used for both the APK verifier and the
14871     * intent filter verifier.
14872     *
14873     * @return verification timeout in milliseconds
14874     */
14875    private long getVerificationTimeout() {
14876        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14877                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14878                DEFAULT_VERIFICATION_TIMEOUT);
14879    }
14880
14881    /**
14882     * Get the default verification agent response code.
14883     *
14884     * @return default verification response code
14885     */
14886    private int getDefaultVerificationResponse(UserHandle user) {
14887        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14888            return PackageManager.VERIFICATION_REJECT;
14889        }
14890        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14891                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14892                DEFAULT_VERIFICATION_RESPONSE);
14893    }
14894
14895    /**
14896     * Check whether or not package verification has been enabled.
14897     *
14898     * @return true if verification should be performed
14899     */
14900    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14901        if (!DEFAULT_VERIFY_ENABLE) {
14902            return false;
14903        }
14904
14905        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14906
14907        // Check if installing from ADB
14908        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14909            // Do not run verification in a test harness environment
14910            if (ActivityManager.isRunningInTestHarness()) {
14911                return false;
14912            }
14913            if (ensureVerifyAppsEnabled) {
14914                return true;
14915            }
14916            // Check if the developer does not want package verification for ADB installs
14917            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14918                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14919                return false;
14920            }
14921        } else {
14922            // only when not installed from ADB, skip verification for instant apps when
14923            // the installer and verifier are the same.
14924            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14925                if (mInstantAppInstallerActivity != null
14926                        && mInstantAppInstallerActivity.packageName.equals(
14927                                mRequiredVerifierPackage)) {
14928                    try {
14929                        mContext.getSystemService(AppOpsManager.class)
14930                                .checkPackage(installerUid, mRequiredVerifierPackage);
14931                        if (DEBUG_VERIFY) {
14932                            Slog.i(TAG, "disable verification for instant app");
14933                        }
14934                        return false;
14935                    } catch (SecurityException ignore) { }
14936                }
14937            }
14938        }
14939
14940        if (ensureVerifyAppsEnabled) {
14941            return true;
14942        }
14943
14944        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14945                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14946    }
14947
14948    @Override
14949    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14950            throws RemoteException {
14951        mContext.enforceCallingOrSelfPermission(
14952                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14953                "Only intentfilter verification agents can verify applications");
14954
14955        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14956        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14957                Binder.getCallingUid(), verificationCode, failedDomains);
14958        msg.arg1 = id;
14959        msg.obj = response;
14960        mHandler.sendMessage(msg);
14961    }
14962
14963    @Override
14964    public int getIntentVerificationStatus(String packageName, int userId) {
14965        final int callingUid = Binder.getCallingUid();
14966        if (getInstantAppPackageName(callingUid) != null) {
14967            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14968        }
14969        synchronized (mPackages) {
14970            final PackageSetting ps = mSettings.mPackages.get(packageName);
14971            if (ps == null
14972                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14973                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14974            }
14975            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14976        }
14977    }
14978
14979    @Override
14980    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14981        mContext.enforceCallingOrSelfPermission(
14982                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14983
14984        boolean result = false;
14985        synchronized (mPackages) {
14986            final PackageSetting ps = mSettings.mPackages.get(packageName);
14987            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14988                return false;
14989            }
14990            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14991        }
14992        if (result) {
14993            scheduleWritePackageRestrictionsLocked(userId);
14994        }
14995        return result;
14996    }
14997
14998    @Override
14999    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15000            String packageName) {
15001        final int callingUid = Binder.getCallingUid();
15002        if (getInstantAppPackageName(callingUid) != null) {
15003            return ParceledListSlice.emptyList();
15004        }
15005        synchronized (mPackages) {
15006            final PackageSetting ps = mSettings.mPackages.get(packageName);
15007            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15008                return ParceledListSlice.emptyList();
15009            }
15010            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15011        }
15012    }
15013
15014    @Override
15015    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15016        if (TextUtils.isEmpty(packageName)) {
15017            return ParceledListSlice.emptyList();
15018        }
15019        final int callingUid = Binder.getCallingUid();
15020        final int callingUserId = UserHandle.getUserId(callingUid);
15021        synchronized (mPackages) {
15022            PackageParser.Package pkg = mPackages.get(packageName);
15023            if (pkg == null || pkg.activities == null) {
15024                return ParceledListSlice.emptyList();
15025            }
15026            if (pkg.mExtras == null) {
15027                return ParceledListSlice.emptyList();
15028            }
15029            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15030            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15031                return ParceledListSlice.emptyList();
15032            }
15033            final int count = pkg.activities.size();
15034            ArrayList<IntentFilter> result = new ArrayList<>();
15035            for (int n=0; n<count; n++) {
15036                PackageParser.Activity activity = pkg.activities.get(n);
15037                if (activity.intents != null && activity.intents.size() > 0) {
15038                    result.addAll(activity.intents);
15039                }
15040            }
15041            return new ParceledListSlice<>(result);
15042        }
15043    }
15044
15045    @Override
15046    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15047        mContext.enforceCallingOrSelfPermission(
15048                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15049
15050        synchronized (mPackages) {
15051            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15052            if (packageName != null) {
15053                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15054                        packageName, userId);
15055            }
15056            return result;
15057        }
15058    }
15059
15060    @Override
15061    public String getDefaultBrowserPackageName(int userId) {
15062        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15063            return null;
15064        }
15065        synchronized (mPackages) {
15066            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15067        }
15068    }
15069
15070    /**
15071     * Get the "allow unknown sources" setting.
15072     *
15073     * @return the current "allow unknown sources" setting
15074     */
15075    private int getUnknownSourcesSettings() {
15076        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15077                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15078                -1);
15079    }
15080
15081    @Override
15082    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15083        final int callingUid = Binder.getCallingUid();
15084        if (getInstantAppPackageName(callingUid) != null) {
15085            return;
15086        }
15087        // writer
15088        synchronized (mPackages) {
15089            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15090            if (targetPackageSetting == null
15091                    || filterAppAccessLPr(
15092                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15093                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15094            }
15095
15096            PackageSetting installerPackageSetting;
15097            if (installerPackageName != null) {
15098                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15099                if (installerPackageSetting == null) {
15100                    throw new IllegalArgumentException("Unknown installer package: "
15101                            + installerPackageName);
15102                }
15103            } else {
15104                installerPackageSetting = null;
15105            }
15106
15107            Signature[] callerSignature;
15108            Object obj = mSettings.getUserIdLPr(callingUid);
15109            if (obj != null) {
15110                if (obj instanceof SharedUserSetting) {
15111                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15112                } else if (obj instanceof PackageSetting) {
15113                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15114                } else {
15115                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15116                }
15117            } else {
15118                throw new SecurityException("Unknown calling UID: " + callingUid);
15119            }
15120
15121            // Verify: can't set installerPackageName to a package that is
15122            // not signed with the same cert as the caller.
15123            if (installerPackageSetting != null) {
15124                if (compareSignatures(callerSignature,
15125                        installerPackageSetting.signatures.mSignatures)
15126                        != PackageManager.SIGNATURE_MATCH) {
15127                    throw new SecurityException(
15128                            "Caller does not have same cert as new installer package "
15129                            + installerPackageName);
15130                }
15131            }
15132
15133            // Verify: if target already has an installer package, it must
15134            // be signed with the same cert as the caller.
15135            if (targetPackageSetting.installerPackageName != null) {
15136                PackageSetting setting = mSettings.mPackages.get(
15137                        targetPackageSetting.installerPackageName);
15138                // If the currently set package isn't valid, then it's always
15139                // okay to change it.
15140                if (setting != null) {
15141                    if (compareSignatures(callerSignature,
15142                            setting.signatures.mSignatures)
15143                            != PackageManager.SIGNATURE_MATCH) {
15144                        throw new SecurityException(
15145                                "Caller does not have same cert as old installer package "
15146                                + targetPackageSetting.installerPackageName);
15147                    }
15148                }
15149            }
15150
15151            // Okay!
15152            targetPackageSetting.installerPackageName = installerPackageName;
15153            if (installerPackageName != null) {
15154                mSettings.mInstallerPackages.add(installerPackageName);
15155            }
15156            scheduleWriteSettingsLocked();
15157        }
15158    }
15159
15160    @Override
15161    public void setApplicationCategoryHint(String packageName, int categoryHint,
15162            String callerPackageName) {
15163        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15164            throw new SecurityException("Instant applications don't have access to this method");
15165        }
15166        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15167                callerPackageName);
15168        synchronized (mPackages) {
15169            PackageSetting ps = mSettings.mPackages.get(packageName);
15170            if (ps == null) {
15171                throw new IllegalArgumentException("Unknown target package " + packageName);
15172            }
15173            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15174                throw new IllegalArgumentException("Unknown target package " + packageName);
15175            }
15176            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15177                throw new IllegalArgumentException("Calling package " + callerPackageName
15178                        + " is not installer for " + packageName);
15179            }
15180
15181            if (ps.categoryHint != categoryHint) {
15182                ps.categoryHint = categoryHint;
15183                scheduleWriteSettingsLocked();
15184            }
15185        }
15186    }
15187
15188    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15189        // Queue up an async operation since the package installation may take a little while.
15190        mHandler.post(new Runnable() {
15191            public void run() {
15192                mHandler.removeCallbacks(this);
15193                 // Result object to be returned
15194                PackageInstalledInfo res = new PackageInstalledInfo();
15195                res.setReturnCode(currentStatus);
15196                res.uid = -1;
15197                res.pkg = null;
15198                res.removedInfo = null;
15199                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15200                    args.doPreInstall(res.returnCode);
15201                    synchronized (mInstallLock) {
15202                        installPackageTracedLI(args, res);
15203                    }
15204                    args.doPostInstall(res.returnCode, res.uid);
15205                }
15206
15207                // A restore should be performed at this point if (a) the install
15208                // succeeded, (b) the operation is not an update, and (c) the new
15209                // package has not opted out of backup participation.
15210                final boolean update = res.removedInfo != null
15211                        && res.removedInfo.removedPackage != null;
15212                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15213                boolean doRestore = !update
15214                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15215
15216                // Set up the post-install work request bookkeeping.  This will be used
15217                // and cleaned up by the post-install event handling regardless of whether
15218                // there's a restore pass performed.  Token values are >= 1.
15219                int token;
15220                if (mNextInstallToken < 0) mNextInstallToken = 1;
15221                token = mNextInstallToken++;
15222
15223                PostInstallData data = new PostInstallData(args, res);
15224                mRunningInstalls.put(token, data);
15225                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15226
15227                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15228                    // Pass responsibility to the Backup Manager.  It will perform a
15229                    // restore if appropriate, then pass responsibility back to the
15230                    // Package Manager to run the post-install observer callbacks
15231                    // and broadcasts.
15232                    IBackupManager bm = IBackupManager.Stub.asInterface(
15233                            ServiceManager.getService(Context.BACKUP_SERVICE));
15234                    if (bm != null) {
15235                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15236                                + " to BM for possible restore");
15237                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15238                        try {
15239                            // TODO: http://b/22388012
15240                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15241                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15242                            } else {
15243                                doRestore = false;
15244                            }
15245                        } catch (RemoteException e) {
15246                            // can't happen; the backup manager is local
15247                        } catch (Exception e) {
15248                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15249                            doRestore = false;
15250                        }
15251                    } else {
15252                        Slog.e(TAG, "Backup Manager not found!");
15253                        doRestore = false;
15254                    }
15255                }
15256
15257                if (!doRestore) {
15258                    // No restore possible, or the Backup Manager was mysteriously not
15259                    // available -- just fire the post-install work request directly.
15260                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15261
15262                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15263
15264                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15265                    mHandler.sendMessage(msg);
15266                }
15267            }
15268        });
15269    }
15270
15271    /**
15272     * Callback from PackageSettings whenever an app is first transitioned out of the
15273     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15274     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15275     * here whether the app is the target of an ongoing install, and only send the
15276     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15277     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15278     * handling.
15279     */
15280    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15281        // Serialize this with the rest of the install-process message chain.  In the
15282        // restore-at-install case, this Runnable will necessarily run before the
15283        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15284        // are coherent.  In the non-restore case, the app has already completed install
15285        // and been launched through some other means, so it is not in a problematic
15286        // state for observers to see the FIRST_LAUNCH signal.
15287        mHandler.post(new Runnable() {
15288            @Override
15289            public void run() {
15290                for (int i = 0; i < mRunningInstalls.size(); i++) {
15291                    final PostInstallData data = mRunningInstalls.valueAt(i);
15292                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15293                        continue;
15294                    }
15295                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15296                        // right package; but is it for the right user?
15297                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15298                            if (userId == data.res.newUsers[uIndex]) {
15299                                if (DEBUG_BACKUP) {
15300                                    Slog.i(TAG, "Package " + pkgName
15301                                            + " being restored so deferring FIRST_LAUNCH");
15302                                }
15303                                return;
15304                            }
15305                        }
15306                    }
15307                }
15308                // didn't find it, so not being restored
15309                if (DEBUG_BACKUP) {
15310                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15311                }
15312                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15313            }
15314        });
15315    }
15316
15317    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15318        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15319                installerPkg, null, userIds);
15320    }
15321
15322    private abstract class HandlerParams {
15323        private static final int MAX_RETRIES = 4;
15324
15325        /**
15326         * Number of times startCopy() has been attempted and had a non-fatal
15327         * error.
15328         */
15329        private int mRetries = 0;
15330
15331        /** User handle for the user requesting the information or installation. */
15332        private final UserHandle mUser;
15333        String traceMethod;
15334        int traceCookie;
15335
15336        HandlerParams(UserHandle user) {
15337            mUser = user;
15338        }
15339
15340        UserHandle getUser() {
15341            return mUser;
15342        }
15343
15344        HandlerParams setTraceMethod(String traceMethod) {
15345            this.traceMethod = traceMethod;
15346            return this;
15347        }
15348
15349        HandlerParams setTraceCookie(int traceCookie) {
15350            this.traceCookie = traceCookie;
15351            return this;
15352        }
15353
15354        final boolean startCopy() {
15355            boolean res;
15356            try {
15357                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15358
15359                if (++mRetries > MAX_RETRIES) {
15360                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15361                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15362                    handleServiceError();
15363                    return false;
15364                } else {
15365                    handleStartCopy();
15366                    res = true;
15367                }
15368            } catch (RemoteException e) {
15369                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15370                mHandler.sendEmptyMessage(MCS_RECONNECT);
15371                res = false;
15372            }
15373            handleReturnCode();
15374            return res;
15375        }
15376
15377        final void serviceError() {
15378            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15379            handleServiceError();
15380            handleReturnCode();
15381        }
15382
15383        abstract void handleStartCopy() throws RemoteException;
15384        abstract void handleServiceError();
15385        abstract void handleReturnCode();
15386    }
15387
15388    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15389        for (File path : paths) {
15390            try {
15391                mcs.clearDirectory(path.getAbsolutePath());
15392            } catch (RemoteException e) {
15393            }
15394        }
15395    }
15396
15397    static class OriginInfo {
15398        /**
15399         * Location where install is coming from, before it has been
15400         * copied/renamed into place. This could be a single monolithic APK
15401         * file, or a cluster directory. This location may be untrusted.
15402         */
15403        final File file;
15404        final String cid;
15405
15406        /**
15407         * Flag indicating that {@link #file} or {@link #cid} has already been
15408         * staged, meaning downstream users don't need to defensively copy the
15409         * contents.
15410         */
15411        final boolean staged;
15412
15413        /**
15414         * Flag indicating that {@link #file} or {@link #cid} is an already
15415         * installed app that is being moved.
15416         */
15417        final boolean existing;
15418
15419        final String resolvedPath;
15420        final File resolvedFile;
15421
15422        static OriginInfo fromNothing() {
15423            return new OriginInfo(null, null, false, false);
15424        }
15425
15426        static OriginInfo fromUntrustedFile(File file) {
15427            return new OriginInfo(file, null, false, false);
15428        }
15429
15430        static OriginInfo fromExistingFile(File file) {
15431            return new OriginInfo(file, null, false, true);
15432        }
15433
15434        static OriginInfo fromStagedFile(File file) {
15435            return new OriginInfo(file, null, true, false);
15436        }
15437
15438        static OriginInfo fromStagedContainer(String cid) {
15439            return new OriginInfo(null, cid, true, false);
15440        }
15441
15442        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15443            this.file = file;
15444            this.cid = cid;
15445            this.staged = staged;
15446            this.existing = existing;
15447
15448            if (cid != null) {
15449                resolvedPath = PackageHelper.getSdDir(cid);
15450                resolvedFile = new File(resolvedPath);
15451            } else if (file != null) {
15452                resolvedPath = file.getAbsolutePath();
15453                resolvedFile = file;
15454            } else {
15455                resolvedPath = null;
15456                resolvedFile = null;
15457            }
15458        }
15459    }
15460
15461    static class MoveInfo {
15462        final int moveId;
15463        final String fromUuid;
15464        final String toUuid;
15465        final String packageName;
15466        final String dataAppName;
15467        final int appId;
15468        final String seinfo;
15469        final int targetSdkVersion;
15470
15471        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15472                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15473            this.moveId = moveId;
15474            this.fromUuid = fromUuid;
15475            this.toUuid = toUuid;
15476            this.packageName = packageName;
15477            this.dataAppName = dataAppName;
15478            this.appId = appId;
15479            this.seinfo = seinfo;
15480            this.targetSdkVersion = targetSdkVersion;
15481        }
15482    }
15483
15484    static class VerificationInfo {
15485        /** A constant used to indicate that a uid value is not present. */
15486        public static final int NO_UID = -1;
15487
15488        /** URI referencing where the package was downloaded from. */
15489        final Uri originatingUri;
15490
15491        /** HTTP referrer URI associated with the originatingURI. */
15492        final Uri referrer;
15493
15494        /** UID of the application that the install request originated from. */
15495        final int originatingUid;
15496
15497        /** UID of application requesting the install */
15498        final int installerUid;
15499
15500        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15501            this.originatingUri = originatingUri;
15502            this.referrer = referrer;
15503            this.originatingUid = originatingUid;
15504            this.installerUid = installerUid;
15505        }
15506    }
15507
15508    class InstallParams extends HandlerParams {
15509        final OriginInfo origin;
15510        final MoveInfo move;
15511        final IPackageInstallObserver2 observer;
15512        int installFlags;
15513        final String installerPackageName;
15514        final String volumeUuid;
15515        private InstallArgs mArgs;
15516        private int mRet;
15517        final String packageAbiOverride;
15518        final String[] grantedRuntimePermissions;
15519        final VerificationInfo verificationInfo;
15520        final Certificate[][] certificates;
15521        final int installReason;
15522
15523        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15524                int installFlags, String installerPackageName, String volumeUuid,
15525                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15526                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15527            super(user);
15528            this.origin = origin;
15529            this.move = move;
15530            this.observer = observer;
15531            this.installFlags = installFlags;
15532            this.installerPackageName = installerPackageName;
15533            this.volumeUuid = volumeUuid;
15534            this.verificationInfo = verificationInfo;
15535            this.packageAbiOverride = packageAbiOverride;
15536            this.grantedRuntimePermissions = grantedPermissions;
15537            this.certificates = certificates;
15538            this.installReason = installReason;
15539        }
15540
15541        @Override
15542        public String toString() {
15543            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15544                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15545        }
15546
15547        private int installLocationPolicy(PackageInfoLite pkgLite) {
15548            String packageName = pkgLite.packageName;
15549            int installLocation = pkgLite.installLocation;
15550            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15551            // reader
15552            synchronized (mPackages) {
15553                // Currently installed package which the new package is attempting to replace or
15554                // null if no such package is installed.
15555                PackageParser.Package installedPkg = mPackages.get(packageName);
15556                // Package which currently owns the data which the new package will own if installed.
15557                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15558                // will be null whereas dataOwnerPkg will contain information about the package
15559                // which was uninstalled while keeping its data.
15560                PackageParser.Package dataOwnerPkg = installedPkg;
15561                if (dataOwnerPkg  == null) {
15562                    PackageSetting ps = mSettings.mPackages.get(packageName);
15563                    if (ps != null) {
15564                        dataOwnerPkg = ps.pkg;
15565                    }
15566                }
15567
15568                if (dataOwnerPkg != null) {
15569                    // If installed, the package will get access to data left on the device by its
15570                    // predecessor. As a security measure, this is permited only if this is not a
15571                    // version downgrade or if the predecessor package is marked as debuggable and
15572                    // a downgrade is explicitly requested.
15573                    //
15574                    // On debuggable platform builds, downgrades are permitted even for
15575                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15576                    // not offer security guarantees and thus it's OK to disable some security
15577                    // mechanisms to make debugging/testing easier on those builds. However, even on
15578                    // debuggable builds downgrades of packages are permitted only if requested via
15579                    // installFlags. This is because we aim to keep the behavior of debuggable
15580                    // platform builds as close as possible to the behavior of non-debuggable
15581                    // platform builds.
15582                    final boolean downgradeRequested =
15583                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15584                    final boolean packageDebuggable =
15585                                (dataOwnerPkg.applicationInfo.flags
15586                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15587                    final boolean downgradePermitted =
15588                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15589                    if (!downgradePermitted) {
15590                        try {
15591                            checkDowngrade(dataOwnerPkg, pkgLite);
15592                        } catch (PackageManagerException e) {
15593                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15594                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15595                        }
15596                    }
15597                }
15598
15599                if (installedPkg != null) {
15600                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15601                        // Check for updated system application.
15602                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15603                            if (onSd) {
15604                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15605                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15606                            }
15607                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15608                        } else {
15609                            if (onSd) {
15610                                // Install flag overrides everything.
15611                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15612                            }
15613                            // If current upgrade specifies particular preference
15614                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15615                                // Application explicitly specified internal.
15616                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15617                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15618                                // App explictly prefers external. Let policy decide
15619                            } else {
15620                                // Prefer previous location
15621                                if (isExternal(installedPkg)) {
15622                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15623                                }
15624                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15625                            }
15626                        }
15627                    } else {
15628                        // Invalid install. Return error code
15629                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15630                    }
15631                }
15632            }
15633            // All the special cases have been taken care of.
15634            // Return result based on recommended install location.
15635            if (onSd) {
15636                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15637            }
15638            return pkgLite.recommendedInstallLocation;
15639        }
15640
15641        /*
15642         * Invoke remote method to get package information and install
15643         * location values. Override install location based on default
15644         * policy if needed and then create install arguments based
15645         * on the install location.
15646         */
15647        public void handleStartCopy() throws RemoteException {
15648            int ret = PackageManager.INSTALL_SUCCEEDED;
15649
15650            // If we're already staged, we've firmly committed to an install location
15651            if (origin.staged) {
15652                if (origin.file != null) {
15653                    installFlags |= PackageManager.INSTALL_INTERNAL;
15654                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15655                } else if (origin.cid != null) {
15656                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15657                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15658                } else {
15659                    throw new IllegalStateException("Invalid stage location");
15660                }
15661            }
15662
15663            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15664            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15665            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15666            PackageInfoLite pkgLite = null;
15667
15668            if (onInt && onSd) {
15669                // Check if both bits are set.
15670                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15671                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15672            } else if (onSd && ephemeral) {
15673                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15674                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15675            } else {
15676                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15677                        packageAbiOverride);
15678
15679                if (DEBUG_EPHEMERAL && ephemeral) {
15680                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15681                }
15682
15683                /*
15684                 * If we have too little free space, try to free cache
15685                 * before giving up.
15686                 */
15687                if (!origin.staged && pkgLite.recommendedInstallLocation
15688                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15689                    // TODO: focus freeing disk space on the target device
15690                    final StorageManager storage = StorageManager.from(mContext);
15691                    final long lowThreshold = storage.getStorageLowBytes(
15692                            Environment.getDataDirectory());
15693
15694                    final long sizeBytes = mContainerService.calculateInstalledSize(
15695                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15696
15697                    try {
15698                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15699                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15700                                installFlags, packageAbiOverride);
15701                    } catch (InstallerException e) {
15702                        Slog.w(TAG, "Failed to free cache", e);
15703                    }
15704
15705                    /*
15706                     * The cache free must have deleted the file we
15707                     * downloaded to install.
15708                     *
15709                     * TODO: fix the "freeCache" call to not delete
15710                     *       the file we care about.
15711                     */
15712                    if (pkgLite.recommendedInstallLocation
15713                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15714                        pkgLite.recommendedInstallLocation
15715                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15716                    }
15717                }
15718            }
15719
15720            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15721                int loc = pkgLite.recommendedInstallLocation;
15722                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15723                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15724                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15725                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15726                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15727                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15728                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15729                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15730                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15731                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15732                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15733                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15734                } else {
15735                    // Override with defaults if needed.
15736                    loc = installLocationPolicy(pkgLite);
15737                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15738                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15739                    } else if (!onSd && !onInt) {
15740                        // Override install location with flags
15741                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15742                            // Set the flag to install on external media.
15743                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15744                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15745                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15746                            if (DEBUG_EPHEMERAL) {
15747                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15748                            }
15749                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15750                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15751                                    |PackageManager.INSTALL_INTERNAL);
15752                        } else {
15753                            // Make sure the flag for installing on external
15754                            // media is unset
15755                            installFlags |= PackageManager.INSTALL_INTERNAL;
15756                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15757                        }
15758                    }
15759                }
15760            }
15761
15762            final InstallArgs args = createInstallArgs(this);
15763            mArgs = args;
15764
15765            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15766                // TODO: http://b/22976637
15767                // Apps installed for "all" users use the device owner to verify the app
15768                UserHandle verifierUser = getUser();
15769                if (verifierUser == UserHandle.ALL) {
15770                    verifierUser = UserHandle.SYSTEM;
15771                }
15772
15773                /*
15774                 * Determine if we have any installed package verifiers. If we
15775                 * do, then we'll defer to them to verify the packages.
15776                 */
15777                final int requiredUid = mRequiredVerifierPackage == null ? -1
15778                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15779                                verifierUser.getIdentifier());
15780                final int installerUid =
15781                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15782                if (!origin.existing && requiredUid != -1
15783                        && isVerificationEnabled(
15784                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15785                    final Intent verification = new Intent(
15786                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15787                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15788                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15789                            PACKAGE_MIME_TYPE);
15790                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15791
15792                    // Query all live verifiers based on current user state
15793                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15794                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15795
15796                    if (DEBUG_VERIFY) {
15797                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15798                                + verification.toString() + " with " + pkgLite.verifiers.length
15799                                + " optional verifiers");
15800                    }
15801
15802                    final int verificationId = mPendingVerificationToken++;
15803
15804                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15805
15806                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15807                            installerPackageName);
15808
15809                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15810                            installFlags);
15811
15812                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15813                            pkgLite.packageName);
15814
15815                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15816                            pkgLite.versionCode);
15817
15818                    if (verificationInfo != null) {
15819                        if (verificationInfo.originatingUri != null) {
15820                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15821                                    verificationInfo.originatingUri);
15822                        }
15823                        if (verificationInfo.referrer != null) {
15824                            verification.putExtra(Intent.EXTRA_REFERRER,
15825                                    verificationInfo.referrer);
15826                        }
15827                        if (verificationInfo.originatingUid >= 0) {
15828                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15829                                    verificationInfo.originatingUid);
15830                        }
15831                        if (verificationInfo.installerUid >= 0) {
15832                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15833                                    verificationInfo.installerUid);
15834                        }
15835                    }
15836
15837                    final PackageVerificationState verificationState = new PackageVerificationState(
15838                            requiredUid, args);
15839
15840                    mPendingVerification.append(verificationId, verificationState);
15841
15842                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15843                            receivers, verificationState);
15844
15845                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15846                    final long idleDuration = getVerificationTimeout();
15847
15848                    /*
15849                     * If any sufficient verifiers were listed in the package
15850                     * manifest, attempt to ask them.
15851                     */
15852                    if (sufficientVerifiers != null) {
15853                        final int N = sufficientVerifiers.size();
15854                        if (N == 0) {
15855                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15856                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15857                        } else {
15858                            for (int i = 0; i < N; i++) {
15859                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15860                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15861                                        verifierComponent.getPackageName(), idleDuration,
15862                                        verifierUser.getIdentifier(), false, "package verifier");
15863
15864                                final Intent sufficientIntent = new Intent(verification);
15865                                sufficientIntent.setComponent(verifierComponent);
15866                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15867                            }
15868                        }
15869                    }
15870
15871                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15872                            mRequiredVerifierPackage, receivers);
15873                    if (ret == PackageManager.INSTALL_SUCCEEDED
15874                            && mRequiredVerifierPackage != null) {
15875                        Trace.asyncTraceBegin(
15876                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15877                        /*
15878                         * Send the intent to the required verification agent,
15879                         * but only start the verification timeout after the
15880                         * target BroadcastReceivers have run.
15881                         */
15882                        verification.setComponent(requiredVerifierComponent);
15883                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15884                                mRequiredVerifierPackage, idleDuration,
15885                                verifierUser.getIdentifier(), false, "package verifier");
15886                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15887                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15888                                new BroadcastReceiver() {
15889                                    @Override
15890                                    public void onReceive(Context context, Intent intent) {
15891                                        final Message msg = mHandler
15892                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15893                                        msg.arg1 = verificationId;
15894                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15895                                    }
15896                                }, null, 0, null, null);
15897
15898                        /*
15899                         * We don't want the copy to proceed until verification
15900                         * succeeds, so null out this field.
15901                         */
15902                        mArgs = null;
15903                    }
15904                } else {
15905                    /*
15906                     * No package verification is enabled, so immediately start
15907                     * the remote call to initiate copy using temporary file.
15908                     */
15909                    ret = args.copyApk(mContainerService, true);
15910                }
15911            }
15912
15913            mRet = ret;
15914        }
15915
15916        @Override
15917        void handleReturnCode() {
15918            // If mArgs is null, then MCS couldn't be reached. When it
15919            // reconnects, it will try again to install. At that point, this
15920            // will succeed.
15921            if (mArgs != null) {
15922                processPendingInstall(mArgs, mRet);
15923            }
15924        }
15925
15926        @Override
15927        void handleServiceError() {
15928            mArgs = createInstallArgs(this);
15929            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15930        }
15931
15932        public boolean isForwardLocked() {
15933            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15934        }
15935    }
15936
15937    /**
15938     * Used during creation of InstallArgs
15939     *
15940     * @param installFlags package installation flags
15941     * @return true if should be installed on external storage
15942     */
15943    private static boolean installOnExternalAsec(int installFlags) {
15944        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15945            return false;
15946        }
15947        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15948            return true;
15949        }
15950        return false;
15951    }
15952
15953    /**
15954     * Used during creation of InstallArgs
15955     *
15956     * @param installFlags package installation flags
15957     * @return true if should be installed as forward locked
15958     */
15959    private static boolean installForwardLocked(int installFlags) {
15960        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15961    }
15962
15963    private InstallArgs createInstallArgs(InstallParams params) {
15964        if (params.move != null) {
15965            return new MoveInstallArgs(params);
15966        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15967            return new AsecInstallArgs(params);
15968        } else {
15969            return new FileInstallArgs(params);
15970        }
15971    }
15972
15973    /**
15974     * Create args that describe an existing installed package. Typically used
15975     * when cleaning up old installs, or used as a move source.
15976     */
15977    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15978            String resourcePath, String[] instructionSets) {
15979        final boolean isInAsec;
15980        if (installOnExternalAsec(installFlags)) {
15981            /* Apps on SD card are always in ASEC containers. */
15982            isInAsec = true;
15983        } else if (installForwardLocked(installFlags)
15984                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15985            /*
15986             * Forward-locked apps are only in ASEC containers if they're the
15987             * new style
15988             */
15989            isInAsec = true;
15990        } else {
15991            isInAsec = false;
15992        }
15993
15994        if (isInAsec) {
15995            return new AsecInstallArgs(codePath, instructionSets,
15996                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15997        } else {
15998            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15999        }
16000    }
16001
16002    static abstract class InstallArgs {
16003        /** @see InstallParams#origin */
16004        final OriginInfo origin;
16005        /** @see InstallParams#move */
16006        final MoveInfo move;
16007
16008        final IPackageInstallObserver2 observer;
16009        // Always refers to PackageManager flags only
16010        final int installFlags;
16011        final String installerPackageName;
16012        final String volumeUuid;
16013        final UserHandle user;
16014        final String abiOverride;
16015        final String[] installGrantPermissions;
16016        /** If non-null, drop an async trace when the install completes */
16017        final String traceMethod;
16018        final int traceCookie;
16019        final Certificate[][] certificates;
16020        final int installReason;
16021
16022        // The list of instruction sets supported by this app. This is currently
16023        // only used during the rmdex() phase to clean up resources. We can get rid of this
16024        // if we move dex files under the common app path.
16025        /* nullable */ String[] instructionSets;
16026
16027        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16028                int installFlags, String installerPackageName, String volumeUuid,
16029                UserHandle user, String[] instructionSets,
16030                String abiOverride, String[] installGrantPermissions,
16031                String traceMethod, int traceCookie, Certificate[][] certificates,
16032                int installReason) {
16033            this.origin = origin;
16034            this.move = move;
16035            this.installFlags = installFlags;
16036            this.observer = observer;
16037            this.installerPackageName = installerPackageName;
16038            this.volumeUuid = volumeUuid;
16039            this.user = user;
16040            this.instructionSets = instructionSets;
16041            this.abiOverride = abiOverride;
16042            this.installGrantPermissions = installGrantPermissions;
16043            this.traceMethod = traceMethod;
16044            this.traceCookie = traceCookie;
16045            this.certificates = certificates;
16046            this.installReason = installReason;
16047        }
16048
16049        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16050        abstract int doPreInstall(int status);
16051
16052        /**
16053         * Rename package into final resting place. All paths on the given
16054         * scanned package should be updated to reflect the rename.
16055         */
16056        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16057        abstract int doPostInstall(int status, int uid);
16058
16059        /** @see PackageSettingBase#codePathString */
16060        abstract String getCodePath();
16061        /** @see PackageSettingBase#resourcePathString */
16062        abstract String getResourcePath();
16063
16064        // Need installer lock especially for dex file removal.
16065        abstract void cleanUpResourcesLI();
16066        abstract boolean doPostDeleteLI(boolean delete);
16067
16068        /**
16069         * Called before the source arguments are copied. This is used mostly
16070         * for MoveParams when it needs to read the source file to put it in the
16071         * destination.
16072         */
16073        int doPreCopy() {
16074            return PackageManager.INSTALL_SUCCEEDED;
16075        }
16076
16077        /**
16078         * Called after the source arguments are copied. This is used mostly for
16079         * MoveParams when it needs to read the source file to put it in the
16080         * destination.
16081         */
16082        int doPostCopy(int uid) {
16083            return PackageManager.INSTALL_SUCCEEDED;
16084        }
16085
16086        protected boolean isFwdLocked() {
16087            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16088        }
16089
16090        protected boolean isExternalAsec() {
16091            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16092        }
16093
16094        protected boolean isEphemeral() {
16095            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16096        }
16097
16098        UserHandle getUser() {
16099            return user;
16100        }
16101    }
16102
16103    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16104        if (!allCodePaths.isEmpty()) {
16105            if (instructionSets == null) {
16106                throw new IllegalStateException("instructionSet == null");
16107            }
16108            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16109            for (String codePath : allCodePaths) {
16110                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16111                    try {
16112                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16113                    } catch (InstallerException ignored) {
16114                    }
16115                }
16116            }
16117        }
16118    }
16119
16120    /**
16121     * Logic to handle installation of non-ASEC applications, including copying
16122     * and renaming logic.
16123     */
16124    class FileInstallArgs extends InstallArgs {
16125        private File codeFile;
16126        private File resourceFile;
16127
16128        // Example topology:
16129        // /data/app/com.example/base.apk
16130        // /data/app/com.example/split_foo.apk
16131        // /data/app/com.example/lib/arm/libfoo.so
16132        // /data/app/com.example/lib/arm64/libfoo.so
16133        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16134
16135        /** New install */
16136        FileInstallArgs(InstallParams params) {
16137            super(params.origin, params.move, params.observer, params.installFlags,
16138                    params.installerPackageName, params.volumeUuid,
16139                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16140                    params.grantedRuntimePermissions,
16141                    params.traceMethod, params.traceCookie, params.certificates,
16142                    params.installReason);
16143            if (isFwdLocked()) {
16144                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16145            }
16146        }
16147
16148        /** Existing install */
16149        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16150            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16151                    null, null, null, 0, null /*certificates*/,
16152                    PackageManager.INSTALL_REASON_UNKNOWN);
16153            this.codeFile = (codePath != null) ? new File(codePath) : null;
16154            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16155        }
16156
16157        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16158            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16159            try {
16160                return doCopyApk(imcs, temp);
16161            } finally {
16162                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16163            }
16164        }
16165
16166        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16167            if (origin.staged) {
16168                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16169                codeFile = origin.file;
16170                resourceFile = origin.file;
16171                return PackageManager.INSTALL_SUCCEEDED;
16172            }
16173
16174            try {
16175                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16176                final File tempDir =
16177                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16178                codeFile = tempDir;
16179                resourceFile = tempDir;
16180            } catch (IOException e) {
16181                Slog.w(TAG, "Failed to create copy file: " + e);
16182                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16183            }
16184
16185            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16186                @Override
16187                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16188                    if (!FileUtils.isValidExtFilename(name)) {
16189                        throw new IllegalArgumentException("Invalid filename: " + name);
16190                    }
16191                    try {
16192                        final File file = new File(codeFile, name);
16193                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16194                                O_RDWR | O_CREAT, 0644);
16195                        Os.chmod(file.getAbsolutePath(), 0644);
16196                        return new ParcelFileDescriptor(fd);
16197                    } catch (ErrnoException e) {
16198                        throw new RemoteException("Failed to open: " + e.getMessage());
16199                    }
16200                }
16201            };
16202
16203            int ret = PackageManager.INSTALL_SUCCEEDED;
16204            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16205            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16206                Slog.e(TAG, "Failed to copy package");
16207                return ret;
16208            }
16209
16210            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16211            NativeLibraryHelper.Handle handle = null;
16212            try {
16213                handle = NativeLibraryHelper.Handle.create(codeFile);
16214                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16215                        abiOverride);
16216            } catch (IOException e) {
16217                Slog.e(TAG, "Copying native libraries failed", e);
16218                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16219            } finally {
16220                IoUtils.closeQuietly(handle);
16221            }
16222
16223            return ret;
16224        }
16225
16226        int doPreInstall(int status) {
16227            if (status != PackageManager.INSTALL_SUCCEEDED) {
16228                cleanUp();
16229            }
16230            return status;
16231        }
16232
16233        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16234            if (status != PackageManager.INSTALL_SUCCEEDED) {
16235                cleanUp();
16236                return false;
16237            }
16238
16239            final File targetDir = codeFile.getParentFile();
16240            final File beforeCodeFile = codeFile;
16241            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16242
16243            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16244            try {
16245                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16246            } catch (ErrnoException e) {
16247                Slog.w(TAG, "Failed to rename", e);
16248                return false;
16249            }
16250
16251            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16252                Slog.w(TAG, "Failed to restorecon");
16253                return false;
16254            }
16255
16256            // Reflect the rename internally
16257            codeFile = afterCodeFile;
16258            resourceFile = afterCodeFile;
16259
16260            // Reflect the rename in scanned details
16261            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16262            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16263                    afterCodeFile, pkg.baseCodePath));
16264            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16265                    afterCodeFile, pkg.splitCodePaths));
16266
16267            // Reflect the rename in app info
16268            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16269            pkg.setApplicationInfoCodePath(pkg.codePath);
16270            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16271            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16272            pkg.setApplicationInfoResourcePath(pkg.codePath);
16273            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16274            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16275
16276            return true;
16277        }
16278
16279        int doPostInstall(int status, int uid) {
16280            if (status != PackageManager.INSTALL_SUCCEEDED) {
16281                cleanUp();
16282            }
16283            return status;
16284        }
16285
16286        @Override
16287        String getCodePath() {
16288            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16289        }
16290
16291        @Override
16292        String getResourcePath() {
16293            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16294        }
16295
16296        private boolean cleanUp() {
16297            if (codeFile == null || !codeFile.exists()) {
16298                return false;
16299            }
16300
16301            removeCodePathLI(codeFile);
16302
16303            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16304                resourceFile.delete();
16305            }
16306
16307            return true;
16308        }
16309
16310        void cleanUpResourcesLI() {
16311            // Try enumerating all code paths before deleting
16312            List<String> allCodePaths = Collections.EMPTY_LIST;
16313            if (codeFile != null && codeFile.exists()) {
16314                try {
16315                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16316                    allCodePaths = pkg.getAllCodePaths();
16317                } catch (PackageParserException e) {
16318                    // Ignored; we tried our best
16319                }
16320            }
16321
16322            cleanUp();
16323            removeDexFiles(allCodePaths, instructionSets);
16324        }
16325
16326        boolean doPostDeleteLI(boolean delete) {
16327            // XXX err, shouldn't we respect the delete flag?
16328            cleanUpResourcesLI();
16329            return true;
16330        }
16331    }
16332
16333    private boolean isAsecExternal(String cid) {
16334        final String asecPath = PackageHelper.getSdFilesystem(cid);
16335        return !asecPath.startsWith(mAsecInternalPath);
16336    }
16337
16338    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16339            PackageManagerException {
16340        if (copyRet < 0) {
16341            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16342                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16343                throw new PackageManagerException(copyRet, message);
16344            }
16345        }
16346    }
16347
16348    /**
16349     * Extract the StorageManagerService "container ID" from the full code path of an
16350     * .apk.
16351     */
16352    static String cidFromCodePath(String fullCodePath) {
16353        int eidx = fullCodePath.lastIndexOf("/");
16354        String subStr1 = fullCodePath.substring(0, eidx);
16355        int sidx = subStr1.lastIndexOf("/");
16356        return subStr1.substring(sidx+1, eidx);
16357    }
16358
16359    /**
16360     * Logic to handle installation of ASEC applications, including copying and
16361     * renaming logic.
16362     */
16363    class AsecInstallArgs extends InstallArgs {
16364        static final String RES_FILE_NAME = "pkg.apk";
16365        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16366
16367        String cid;
16368        String packagePath;
16369        String resourcePath;
16370
16371        /** New install */
16372        AsecInstallArgs(InstallParams params) {
16373            super(params.origin, params.move, params.observer, params.installFlags,
16374                    params.installerPackageName, params.volumeUuid,
16375                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16376                    params.grantedRuntimePermissions,
16377                    params.traceMethod, params.traceCookie, params.certificates,
16378                    params.installReason);
16379        }
16380
16381        /** Existing install */
16382        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16383                        boolean isExternal, boolean isForwardLocked) {
16384            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16385                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16386                    instructionSets, null, null, null, 0, null /*certificates*/,
16387                    PackageManager.INSTALL_REASON_UNKNOWN);
16388            // Hackily pretend we're still looking at a full code path
16389            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16390                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16391            }
16392
16393            // Extract cid from fullCodePath
16394            int eidx = fullCodePath.lastIndexOf("/");
16395            String subStr1 = fullCodePath.substring(0, eidx);
16396            int sidx = subStr1.lastIndexOf("/");
16397            cid = subStr1.substring(sidx+1, eidx);
16398            setMountPath(subStr1);
16399        }
16400
16401        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16402            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16403                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16404                    instructionSets, null, null, null, 0, null /*certificates*/,
16405                    PackageManager.INSTALL_REASON_UNKNOWN);
16406            this.cid = cid;
16407            setMountPath(PackageHelper.getSdDir(cid));
16408        }
16409
16410        void createCopyFile() {
16411            cid = mInstallerService.allocateExternalStageCidLegacy();
16412        }
16413
16414        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16415            if (origin.staged && origin.cid != null) {
16416                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16417                cid = origin.cid;
16418                setMountPath(PackageHelper.getSdDir(cid));
16419                return PackageManager.INSTALL_SUCCEEDED;
16420            }
16421
16422            if (temp) {
16423                createCopyFile();
16424            } else {
16425                /*
16426                 * Pre-emptively destroy the container since it's destroyed if
16427                 * copying fails due to it existing anyway.
16428                 */
16429                PackageHelper.destroySdDir(cid);
16430            }
16431
16432            final String newMountPath = imcs.copyPackageToContainer(
16433                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16434                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16435
16436            if (newMountPath != null) {
16437                setMountPath(newMountPath);
16438                return PackageManager.INSTALL_SUCCEEDED;
16439            } else {
16440                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16441            }
16442        }
16443
16444        @Override
16445        String getCodePath() {
16446            return packagePath;
16447        }
16448
16449        @Override
16450        String getResourcePath() {
16451            return resourcePath;
16452        }
16453
16454        int doPreInstall(int status) {
16455            if (status != PackageManager.INSTALL_SUCCEEDED) {
16456                // Destroy container
16457                PackageHelper.destroySdDir(cid);
16458            } else {
16459                boolean mounted = PackageHelper.isContainerMounted(cid);
16460                if (!mounted) {
16461                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16462                            Process.SYSTEM_UID);
16463                    if (newMountPath != null) {
16464                        setMountPath(newMountPath);
16465                    } else {
16466                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16467                    }
16468                }
16469            }
16470            return status;
16471        }
16472
16473        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16474            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16475            String newMountPath = null;
16476            if (PackageHelper.isContainerMounted(cid)) {
16477                // Unmount the container
16478                if (!PackageHelper.unMountSdDir(cid)) {
16479                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16480                    return false;
16481                }
16482            }
16483            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16484                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16485                        " which might be stale. Will try to clean up.");
16486                // Clean up the stale container and proceed to recreate.
16487                if (!PackageHelper.destroySdDir(newCacheId)) {
16488                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16489                    return false;
16490                }
16491                // Successfully cleaned up stale container. Try to rename again.
16492                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16493                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16494                            + " inspite of cleaning it up.");
16495                    return false;
16496                }
16497            }
16498            if (!PackageHelper.isContainerMounted(newCacheId)) {
16499                Slog.w(TAG, "Mounting container " + newCacheId);
16500                newMountPath = PackageHelper.mountSdDir(newCacheId,
16501                        getEncryptKey(), Process.SYSTEM_UID);
16502            } else {
16503                newMountPath = PackageHelper.getSdDir(newCacheId);
16504            }
16505            if (newMountPath == null) {
16506                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16507                return false;
16508            }
16509            Log.i(TAG, "Succesfully renamed " + cid +
16510                    " to " + newCacheId +
16511                    " at new path: " + newMountPath);
16512            cid = newCacheId;
16513
16514            final File beforeCodeFile = new File(packagePath);
16515            setMountPath(newMountPath);
16516            final File afterCodeFile = new File(packagePath);
16517
16518            // Reflect the rename in scanned details
16519            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16520            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16521                    afterCodeFile, pkg.baseCodePath));
16522            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16523                    afterCodeFile, pkg.splitCodePaths));
16524
16525            // Reflect the rename in app info
16526            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16527            pkg.setApplicationInfoCodePath(pkg.codePath);
16528            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16529            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16530            pkg.setApplicationInfoResourcePath(pkg.codePath);
16531            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16532            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16533
16534            return true;
16535        }
16536
16537        private void setMountPath(String mountPath) {
16538            final File mountFile = new File(mountPath);
16539
16540            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16541            if (monolithicFile.exists()) {
16542                packagePath = monolithicFile.getAbsolutePath();
16543                if (isFwdLocked()) {
16544                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16545                } else {
16546                    resourcePath = packagePath;
16547                }
16548            } else {
16549                packagePath = mountFile.getAbsolutePath();
16550                resourcePath = packagePath;
16551            }
16552        }
16553
16554        int doPostInstall(int status, int uid) {
16555            if (status != PackageManager.INSTALL_SUCCEEDED) {
16556                cleanUp();
16557            } else {
16558                final int groupOwner;
16559                final String protectedFile;
16560                if (isFwdLocked()) {
16561                    groupOwner = UserHandle.getSharedAppGid(uid);
16562                    protectedFile = RES_FILE_NAME;
16563                } else {
16564                    groupOwner = -1;
16565                    protectedFile = null;
16566                }
16567
16568                if (uid < Process.FIRST_APPLICATION_UID
16569                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16570                    Slog.e(TAG, "Failed to finalize " + cid);
16571                    PackageHelper.destroySdDir(cid);
16572                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16573                }
16574
16575                boolean mounted = PackageHelper.isContainerMounted(cid);
16576                if (!mounted) {
16577                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16578                }
16579            }
16580            return status;
16581        }
16582
16583        private void cleanUp() {
16584            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16585
16586            // Destroy secure container
16587            PackageHelper.destroySdDir(cid);
16588        }
16589
16590        private List<String> getAllCodePaths() {
16591            final File codeFile = new File(getCodePath());
16592            if (codeFile != null && codeFile.exists()) {
16593                try {
16594                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16595                    return pkg.getAllCodePaths();
16596                } catch (PackageParserException e) {
16597                    // Ignored; we tried our best
16598                }
16599            }
16600            return Collections.EMPTY_LIST;
16601        }
16602
16603        void cleanUpResourcesLI() {
16604            // Enumerate all code paths before deleting
16605            cleanUpResourcesLI(getAllCodePaths());
16606        }
16607
16608        private void cleanUpResourcesLI(List<String> allCodePaths) {
16609            cleanUp();
16610            removeDexFiles(allCodePaths, instructionSets);
16611        }
16612
16613        String getPackageName() {
16614            return getAsecPackageName(cid);
16615        }
16616
16617        boolean doPostDeleteLI(boolean delete) {
16618            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16619            final List<String> allCodePaths = getAllCodePaths();
16620            boolean mounted = PackageHelper.isContainerMounted(cid);
16621            if (mounted) {
16622                // Unmount first
16623                if (PackageHelper.unMountSdDir(cid)) {
16624                    mounted = false;
16625                }
16626            }
16627            if (!mounted && delete) {
16628                cleanUpResourcesLI(allCodePaths);
16629            }
16630            return !mounted;
16631        }
16632
16633        @Override
16634        int doPreCopy() {
16635            if (isFwdLocked()) {
16636                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16637                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16638                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16639                }
16640            }
16641
16642            return PackageManager.INSTALL_SUCCEEDED;
16643        }
16644
16645        @Override
16646        int doPostCopy(int uid) {
16647            if (isFwdLocked()) {
16648                if (uid < Process.FIRST_APPLICATION_UID
16649                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16650                                RES_FILE_NAME)) {
16651                    Slog.e(TAG, "Failed to finalize " + cid);
16652                    PackageHelper.destroySdDir(cid);
16653                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16654                }
16655            }
16656
16657            return PackageManager.INSTALL_SUCCEEDED;
16658        }
16659    }
16660
16661    /**
16662     * Logic to handle movement of existing installed applications.
16663     */
16664    class MoveInstallArgs extends InstallArgs {
16665        private File codeFile;
16666        private File resourceFile;
16667
16668        /** New install */
16669        MoveInstallArgs(InstallParams params) {
16670            super(params.origin, params.move, params.observer, params.installFlags,
16671                    params.installerPackageName, params.volumeUuid,
16672                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16673                    params.grantedRuntimePermissions,
16674                    params.traceMethod, params.traceCookie, params.certificates,
16675                    params.installReason);
16676        }
16677
16678        int copyApk(IMediaContainerService imcs, boolean temp) {
16679            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16680                    + move.fromUuid + " to " + move.toUuid);
16681            synchronized (mInstaller) {
16682                try {
16683                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16684                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16685                } catch (InstallerException e) {
16686                    Slog.w(TAG, "Failed to move app", e);
16687                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16688                }
16689            }
16690
16691            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16692            resourceFile = codeFile;
16693            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16694
16695            return PackageManager.INSTALL_SUCCEEDED;
16696        }
16697
16698        int doPreInstall(int status) {
16699            if (status != PackageManager.INSTALL_SUCCEEDED) {
16700                cleanUp(move.toUuid);
16701            }
16702            return status;
16703        }
16704
16705        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16706            if (status != PackageManager.INSTALL_SUCCEEDED) {
16707                cleanUp(move.toUuid);
16708                return false;
16709            }
16710
16711            // Reflect the move in app info
16712            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16713            pkg.setApplicationInfoCodePath(pkg.codePath);
16714            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16715            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16716            pkg.setApplicationInfoResourcePath(pkg.codePath);
16717            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16718            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16719
16720            return true;
16721        }
16722
16723        int doPostInstall(int status, int uid) {
16724            if (status == PackageManager.INSTALL_SUCCEEDED) {
16725                cleanUp(move.fromUuid);
16726            } else {
16727                cleanUp(move.toUuid);
16728            }
16729            return status;
16730        }
16731
16732        @Override
16733        String getCodePath() {
16734            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16735        }
16736
16737        @Override
16738        String getResourcePath() {
16739            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16740        }
16741
16742        private boolean cleanUp(String volumeUuid) {
16743            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16744                    move.dataAppName);
16745            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16746            final int[] userIds = sUserManager.getUserIds();
16747            synchronized (mInstallLock) {
16748                // Clean up both app data and code
16749                // All package moves are frozen until finished
16750                for (int userId : userIds) {
16751                    try {
16752                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16753                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16754                    } catch (InstallerException e) {
16755                        Slog.w(TAG, String.valueOf(e));
16756                    }
16757                }
16758                removeCodePathLI(codeFile);
16759            }
16760            return true;
16761        }
16762
16763        void cleanUpResourcesLI() {
16764            throw new UnsupportedOperationException();
16765        }
16766
16767        boolean doPostDeleteLI(boolean delete) {
16768            throw new UnsupportedOperationException();
16769        }
16770    }
16771
16772    static String getAsecPackageName(String packageCid) {
16773        int idx = packageCid.lastIndexOf("-");
16774        if (idx == -1) {
16775            return packageCid;
16776        }
16777        return packageCid.substring(0, idx);
16778    }
16779
16780    // Utility method used to create code paths based on package name and available index.
16781    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16782        String idxStr = "";
16783        int idx = 1;
16784        // Fall back to default value of idx=1 if prefix is not
16785        // part of oldCodePath
16786        if (oldCodePath != null) {
16787            String subStr = oldCodePath;
16788            // Drop the suffix right away
16789            if (suffix != null && subStr.endsWith(suffix)) {
16790                subStr = subStr.substring(0, subStr.length() - suffix.length());
16791            }
16792            // If oldCodePath already contains prefix find out the
16793            // ending index to either increment or decrement.
16794            int sidx = subStr.lastIndexOf(prefix);
16795            if (sidx != -1) {
16796                subStr = subStr.substring(sidx + prefix.length());
16797                if (subStr != null) {
16798                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16799                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16800                    }
16801                    try {
16802                        idx = Integer.parseInt(subStr);
16803                        if (idx <= 1) {
16804                            idx++;
16805                        } else {
16806                            idx--;
16807                        }
16808                    } catch(NumberFormatException e) {
16809                    }
16810                }
16811            }
16812        }
16813        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16814        return prefix + idxStr;
16815    }
16816
16817    private File getNextCodePath(File targetDir, String packageName) {
16818        File result;
16819        SecureRandom random = new SecureRandom();
16820        byte[] bytes = new byte[16];
16821        do {
16822            random.nextBytes(bytes);
16823            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16824            result = new File(targetDir, packageName + "-" + suffix);
16825        } while (result.exists());
16826        return result;
16827    }
16828
16829    // Utility method that returns the relative package path with respect
16830    // to the installation directory. Like say for /data/data/com.test-1.apk
16831    // string com.test-1 is returned.
16832    static String deriveCodePathName(String codePath) {
16833        if (codePath == null) {
16834            return null;
16835        }
16836        final File codeFile = new File(codePath);
16837        final String name = codeFile.getName();
16838        if (codeFile.isDirectory()) {
16839            return name;
16840        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16841            final int lastDot = name.lastIndexOf('.');
16842            return name.substring(0, lastDot);
16843        } else {
16844            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16845            return null;
16846        }
16847    }
16848
16849    static class PackageInstalledInfo {
16850        String name;
16851        int uid;
16852        // The set of users that originally had this package installed.
16853        int[] origUsers;
16854        // The set of users that now have this package installed.
16855        int[] newUsers;
16856        PackageParser.Package pkg;
16857        int returnCode;
16858        String returnMsg;
16859        PackageRemovedInfo removedInfo;
16860        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16861
16862        public void setError(int code, String msg) {
16863            setReturnCode(code);
16864            setReturnMessage(msg);
16865            Slog.w(TAG, msg);
16866        }
16867
16868        public void setError(String msg, PackageParserException e) {
16869            setReturnCode(e.error);
16870            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16871            Slog.w(TAG, msg, e);
16872        }
16873
16874        public void setError(String msg, PackageManagerException e) {
16875            returnCode = e.error;
16876            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16877            Slog.w(TAG, msg, e);
16878        }
16879
16880        public void setReturnCode(int returnCode) {
16881            this.returnCode = returnCode;
16882            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16883            for (int i = 0; i < childCount; i++) {
16884                addedChildPackages.valueAt(i).returnCode = returnCode;
16885            }
16886        }
16887
16888        private void setReturnMessage(String returnMsg) {
16889            this.returnMsg = returnMsg;
16890            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16891            for (int i = 0; i < childCount; i++) {
16892                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16893            }
16894        }
16895
16896        // In some error cases we want to convey more info back to the observer
16897        String origPackage;
16898        String origPermission;
16899    }
16900
16901    /*
16902     * Install a non-existing package.
16903     */
16904    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16905            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16906            PackageInstalledInfo res, int installReason) {
16907        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16908
16909        // Remember this for later, in case we need to rollback this install
16910        String pkgName = pkg.packageName;
16911
16912        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16913
16914        synchronized(mPackages) {
16915            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16916            if (renamedPackage != null) {
16917                // A package with the same name is already installed, though
16918                // it has been renamed to an older name.  The package we
16919                // are trying to install should be installed as an update to
16920                // the existing one, but that has not been requested, so bail.
16921                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16922                        + " without first uninstalling package running as "
16923                        + renamedPackage);
16924                return;
16925            }
16926            if (mPackages.containsKey(pkgName)) {
16927                // Don't allow installation over an existing package with the same name.
16928                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16929                        + " without first uninstalling.");
16930                return;
16931            }
16932        }
16933
16934        try {
16935            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16936                    System.currentTimeMillis(), user);
16937
16938            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16939
16940            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16941                prepareAppDataAfterInstallLIF(newPackage);
16942
16943            } else {
16944                // Remove package from internal structures, but keep around any
16945                // data that might have already existed
16946                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16947                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16948            }
16949        } catch (PackageManagerException e) {
16950            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16951        }
16952
16953        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16954    }
16955
16956    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16957        // Can't rotate keys during boot or if sharedUser.
16958        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16959                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16960            return false;
16961        }
16962        // app is using upgradeKeySets; make sure all are valid
16963        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16964        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16965        for (int i = 0; i < upgradeKeySets.length; i++) {
16966            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16967                Slog.wtf(TAG, "Package "
16968                         + (oldPs.name != null ? oldPs.name : "<null>")
16969                         + " contains upgrade-key-set reference to unknown key-set: "
16970                         + upgradeKeySets[i]
16971                         + " reverting to signatures check.");
16972                return false;
16973            }
16974        }
16975        return true;
16976    }
16977
16978    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16979        // Upgrade keysets are being used.  Determine if new package has a superset of the
16980        // required keys.
16981        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16982        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16983        for (int i = 0; i < upgradeKeySets.length; i++) {
16984            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16985            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16986                return true;
16987            }
16988        }
16989        return false;
16990    }
16991
16992    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16993        try (DigestInputStream digestStream =
16994                new DigestInputStream(new FileInputStream(file), digest)) {
16995            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16996        }
16997    }
16998
16999    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17000            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17001            int installReason) {
17002        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17003
17004        final PackageParser.Package oldPackage;
17005        final PackageSetting ps;
17006        final String pkgName = pkg.packageName;
17007        final int[] allUsers;
17008        final int[] installedUsers;
17009
17010        synchronized(mPackages) {
17011            oldPackage = mPackages.get(pkgName);
17012            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17013
17014            // don't allow upgrade to target a release SDK from a pre-release SDK
17015            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17016                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17017            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17018                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17019            if (oldTargetsPreRelease
17020                    && !newTargetsPreRelease
17021                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17022                Slog.w(TAG, "Can't install package targeting released sdk");
17023                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17024                return;
17025            }
17026
17027            ps = mSettings.mPackages.get(pkgName);
17028
17029            // verify signatures are valid
17030            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17031                if (!checkUpgradeKeySetLP(ps, pkg)) {
17032                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17033                            "New package not signed by keys specified by upgrade-keysets: "
17034                                    + pkgName);
17035                    return;
17036                }
17037            } else {
17038                // default to original signature matching
17039                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17040                        != PackageManager.SIGNATURE_MATCH) {
17041                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17042                            "New package has a different signature: " + pkgName);
17043                    return;
17044                }
17045            }
17046
17047            // don't allow a system upgrade unless the upgrade hash matches
17048            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17049                byte[] digestBytes = null;
17050                try {
17051                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17052                    updateDigest(digest, new File(pkg.baseCodePath));
17053                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17054                        for (String path : pkg.splitCodePaths) {
17055                            updateDigest(digest, new File(path));
17056                        }
17057                    }
17058                    digestBytes = digest.digest();
17059                } catch (NoSuchAlgorithmException | IOException e) {
17060                    res.setError(INSTALL_FAILED_INVALID_APK,
17061                            "Could not compute hash: " + pkgName);
17062                    return;
17063                }
17064                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17065                    res.setError(INSTALL_FAILED_INVALID_APK,
17066                            "New package fails restrict-update check: " + pkgName);
17067                    return;
17068                }
17069                // retain upgrade restriction
17070                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17071            }
17072
17073            // Check for shared user id changes
17074            String invalidPackageName =
17075                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17076            if (invalidPackageName != null) {
17077                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17078                        "Package " + invalidPackageName + " tried to change user "
17079                                + oldPackage.mSharedUserId);
17080                return;
17081            }
17082
17083            // In case of rollback, remember per-user/profile install state
17084            allUsers = sUserManager.getUserIds();
17085            installedUsers = ps.queryInstalledUsers(allUsers, true);
17086
17087            // don't allow an upgrade from full to ephemeral
17088            if (isInstantApp) {
17089                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17090                    for (int currentUser : allUsers) {
17091                        if (!ps.getInstantApp(currentUser)) {
17092                            // can't downgrade from full to instant
17093                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17094                                    + " for user: " + currentUser);
17095                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17096                            return;
17097                        }
17098                    }
17099                } else if (!ps.getInstantApp(user.getIdentifier())) {
17100                    // can't downgrade from full to instant
17101                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17102                            + " for user: " + user.getIdentifier());
17103                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17104                    return;
17105                }
17106            }
17107        }
17108
17109        // Update what is removed
17110        res.removedInfo = new PackageRemovedInfo(this);
17111        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17112        res.removedInfo.removedPackage = oldPackage.packageName;
17113        res.removedInfo.installerPackageName = ps.installerPackageName;
17114        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17115        res.removedInfo.isUpdate = true;
17116        res.removedInfo.origUsers = installedUsers;
17117        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17118        for (int i = 0; i < installedUsers.length; i++) {
17119            final int userId = installedUsers[i];
17120            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17121        }
17122
17123        final int childCount = (oldPackage.childPackages != null)
17124                ? oldPackage.childPackages.size() : 0;
17125        for (int i = 0; i < childCount; i++) {
17126            boolean childPackageUpdated = false;
17127            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17128            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17129            if (res.addedChildPackages != null) {
17130                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17131                if (childRes != null) {
17132                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17133                    childRes.removedInfo.removedPackage = childPkg.packageName;
17134                    if (childPs != null) {
17135                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17136                    }
17137                    childRes.removedInfo.isUpdate = true;
17138                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17139                    childPackageUpdated = true;
17140                }
17141            }
17142            if (!childPackageUpdated) {
17143                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17144                childRemovedRes.removedPackage = childPkg.packageName;
17145                if (childPs != null) {
17146                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17147                }
17148                childRemovedRes.isUpdate = false;
17149                childRemovedRes.dataRemoved = true;
17150                synchronized (mPackages) {
17151                    if (childPs != null) {
17152                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17153                    }
17154                }
17155                if (res.removedInfo.removedChildPackages == null) {
17156                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17157                }
17158                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17159            }
17160        }
17161
17162        boolean sysPkg = (isSystemApp(oldPackage));
17163        if (sysPkg) {
17164            // Set the system/privileged flags as needed
17165            final boolean privileged =
17166                    (oldPackage.applicationInfo.privateFlags
17167                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17168            final int systemPolicyFlags = policyFlags
17169                    | PackageParser.PARSE_IS_SYSTEM
17170                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17171
17172            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17173                    user, allUsers, installerPackageName, res, installReason);
17174        } else {
17175            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17176                    user, allUsers, installerPackageName, res, installReason);
17177        }
17178    }
17179
17180    @Override
17181    public List<String> getPreviousCodePaths(String packageName) {
17182        final int callingUid = Binder.getCallingUid();
17183        final List<String> result = new ArrayList<>();
17184        if (getInstantAppPackageName(callingUid) != null) {
17185            return result;
17186        }
17187        final PackageSetting ps = mSettings.mPackages.get(packageName);
17188        if (ps != null
17189                && ps.oldCodePaths != null
17190                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17191            result.addAll(ps.oldCodePaths);
17192        }
17193        return result;
17194    }
17195
17196    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17197            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17198            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17199            int installReason) {
17200        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17201                + deletedPackage);
17202
17203        String pkgName = deletedPackage.packageName;
17204        boolean deletedPkg = true;
17205        boolean addedPkg = false;
17206        boolean updatedSettings = false;
17207        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17208        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17209                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17210
17211        final long origUpdateTime = (pkg.mExtras != null)
17212                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17213
17214        // First delete the existing package while retaining the data directory
17215        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17216                res.removedInfo, true, pkg)) {
17217            // If the existing package wasn't successfully deleted
17218            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17219            deletedPkg = false;
17220        } else {
17221            // Successfully deleted the old package; proceed with replace.
17222
17223            // If deleted package lived in a container, give users a chance to
17224            // relinquish resources before killing.
17225            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17226                if (DEBUG_INSTALL) {
17227                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17228                }
17229                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17230                final ArrayList<String> pkgList = new ArrayList<String>(1);
17231                pkgList.add(deletedPackage.applicationInfo.packageName);
17232                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17233            }
17234
17235            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17236                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17237            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17238
17239            try {
17240                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17241                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17242                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17243                        installReason);
17244
17245                // Update the in-memory copy of the previous code paths.
17246                PackageSetting ps = mSettings.mPackages.get(pkgName);
17247                if (!killApp) {
17248                    if (ps.oldCodePaths == null) {
17249                        ps.oldCodePaths = new ArraySet<>();
17250                    }
17251                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17252                    if (deletedPackage.splitCodePaths != null) {
17253                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17254                    }
17255                } else {
17256                    ps.oldCodePaths = null;
17257                }
17258                if (ps.childPackageNames != null) {
17259                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17260                        final String childPkgName = ps.childPackageNames.get(i);
17261                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17262                        childPs.oldCodePaths = ps.oldCodePaths;
17263                    }
17264                }
17265                // set instant app status, but, only if it's explicitly specified
17266                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17267                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17268                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17269                prepareAppDataAfterInstallLIF(newPackage);
17270                addedPkg = true;
17271                mDexManager.notifyPackageUpdated(newPackage.packageName,
17272                        newPackage.baseCodePath, newPackage.splitCodePaths);
17273            } catch (PackageManagerException e) {
17274                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17275            }
17276        }
17277
17278        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17279            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17280
17281            // Revert all internal state mutations and added folders for the failed install
17282            if (addedPkg) {
17283                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17284                        res.removedInfo, true, null);
17285            }
17286
17287            // Restore the old package
17288            if (deletedPkg) {
17289                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17290                File restoreFile = new File(deletedPackage.codePath);
17291                // Parse old package
17292                boolean oldExternal = isExternal(deletedPackage);
17293                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17294                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17295                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17296                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17297                try {
17298                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17299                            null);
17300                } catch (PackageManagerException e) {
17301                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17302                            + e.getMessage());
17303                    return;
17304                }
17305
17306                synchronized (mPackages) {
17307                    // Ensure the installer package name up to date
17308                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17309
17310                    // Update permissions for restored package
17311                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17312
17313                    mSettings.writeLPr();
17314                }
17315
17316                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17317            }
17318        } else {
17319            synchronized (mPackages) {
17320                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17321                if (ps != null) {
17322                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17323                    if (res.removedInfo.removedChildPackages != null) {
17324                        final int childCount = res.removedInfo.removedChildPackages.size();
17325                        // Iterate in reverse as we may modify the collection
17326                        for (int i = childCount - 1; i >= 0; i--) {
17327                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17328                            if (res.addedChildPackages.containsKey(childPackageName)) {
17329                                res.removedInfo.removedChildPackages.removeAt(i);
17330                            } else {
17331                                PackageRemovedInfo childInfo = res.removedInfo
17332                                        .removedChildPackages.valueAt(i);
17333                                childInfo.removedForAllUsers = mPackages.get(
17334                                        childInfo.removedPackage) == null;
17335                            }
17336                        }
17337                    }
17338                }
17339            }
17340        }
17341    }
17342
17343    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17344            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17345            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17346            int installReason) {
17347        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17348                + ", old=" + deletedPackage);
17349
17350        final boolean disabledSystem;
17351
17352        // Remove existing system package
17353        removePackageLI(deletedPackage, true);
17354
17355        synchronized (mPackages) {
17356            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17357        }
17358        if (!disabledSystem) {
17359            // We didn't need to disable the .apk as a current system package,
17360            // which means we are replacing another update that is already
17361            // installed.  We need to make sure to delete the older one's .apk.
17362            res.removedInfo.args = createInstallArgsForExisting(0,
17363                    deletedPackage.applicationInfo.getCodePath(),
17364                    deletedPackage.applicationInfo.getResourcePath(),
17365                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17366        } else {
17367            res.removedInfo.args = null;
17368        }
17369
17370        // Successfully disabled the old package. Now proceed with re-installation
17371        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17372                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17373        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17374
17375        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17376        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17377                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17378
17379        PackageParser.Package newPackage = null;
17380        try {
17381            // Add the package to the internal data structures
17382            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17383
17384            // Set the update and install times
17385            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17386            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17387                    System.currentTimeMillis());
17388
17389            // Update the package dynamic state if succeeded
17390            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17391                // Now that the install succeeded make sure we remove data
17392                // directories for any child package the update removed.
17393                final int deletedChildCount = (deletedPackage.childPackages != null)
17394                        ? deletedPackage.childPackages.size() : 0;
17395                final int newChildCount = (newPackage.childPackages != null)
17396                        ? newPackage.childPackages.size() : 0;
17397                for (int i = 0; i < deletedChildCount; i++) {
17398                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17399                    boolean childPackageDeleted = true;
17400                    for (int j = 0; j < newChildCount; j++) {
17401                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17402                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17403                            childPackageDeleted = false;
17404                            break;
17405                        }
17406                    }
17407                    if (childPackageDeleted) {
17408                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17409                                deletedChildPkg.packageName);
17410                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17411                            PackageRemovedInfo removedChildRes = res.removedInfo
17412                                    .removedChildPackages.get(deletedChildPkg.packageName);
17413                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17414                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17415                        }
17416                    }
17417                }
17418
17419                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17420                        installReason);
17421                prepareAppDataAfterInstallLIF(newPackage);
17422
17423                mDexManager.notifyPackageUpdated(newPackage.packageName,
17424                            newPackage.baseCodePath, newPackage.splitCodePaths);
17425            }
17426        } catch (PackageManagerException e) {
17427            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17428            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17429        }
17430
17431        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17432            // Re installation failed. Restore old information
17433            // Remove new pkg information
17434            if (newPackage != null) {
17435                removeInstalledPackageLI(newPackage, true);
17436            }
17437            // Add back the old system package
17438            try {
17439                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17440            } catch (PackageManagerException e) {
17441                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17442            }
17443
17444            synchronized (mPackages) {
17445                if (disabledSystem) {
17446                    enableSystemPackageLPw(deletedPackage);
17447                }
17448
17449                // Ensure the installer package name up to date
17450                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17451
17452                // Update permissions for restored package
17453                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17454
17455                mSettings.writeLPr();
17456            }
17457
17458            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17459                    + " after failed upgrade");
17460        }
17461    }
17462
17463    /**
17464     * Checks whether the parent or any of the child packages have a change shared
17465     * user. For a package to be a valid update the shred users of the parent and
17466     * the children should match. We may later support changing child shared users.
17467     * @param oldPkg The updated package.
17468     * @param newPkg The update package.
17469     * @return The shared user that change between the versions.
17470     */
17471    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17472            PackageParser.Package newPkg) {
17473        // Check parent shared user
17474        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17475            return newPkg.packageName;
17476        }
17477        // Check child shared users
17478        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17479        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17480        for (int i = 0; i < newChildCount; i++) {
17481            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17482            // If this child was present, did it have the same shared user?
17483            for (int j = 0; j < oldChildCount; j++) {
17484                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17485                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17486                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17487                    return newChildPkg.packageName;
17488                }
17489            }
17490        }
17491        return null;
17492    }
17493
17494    private void removeNativeBinariesLI(PackageSetting ps) {
17495        // Remove the lib path for the parent package
17496        if (ps != null) {
17497            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17498            // Remove the lib path for the child packages
17499            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17500            for (int i = 0; i < childCount; i++) {
17501                PackageSetting childPs = null;
17502                synchronized (mPackages) {
17503                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17504                }
17505                if (childPs != null) {
17506                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17507                            .legacyNativeLibraryPathString);
17508                }
17509            }
17510        }
17511    }
17512
17513    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17514        // Enable the parent package
17515        mSettings.enableSystemPackageLPw(pkg.packageName);
17516        // Enable the child packages
17517        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17518        for (int i = 0; i < childCount; i++) {
17519            PackageParser.Package childPkg = pkg.childPackages.get(i);
17520            mSettings.enableSystemPackageLPw(childPkg.packageName);
17521        }
17522    }
17523
17524    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17525            PackageParser.Package newPkg) {
17526        // Disable the parent package (parent always replaced)
17527        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17528        // Disable the child packages
17529        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17530        for (int i = 0; i < childCount; i++) {
17531            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17532            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17533            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17534        }
17535        return disabled;
17536    }
17537
17538    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17539            String installerPackageName) {
17540        // Enable the parent package
17541        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17542        // Enable the child packages
17543        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17544        for (int i = 0; i < childCount; i++) {
17545            PackageParser.Package childPkg = pkg.childPackages.get(i);
17546            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17547        }
17548    }
17549
17550    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17551        // Collect all used permissions in the UID
17552        ArraySet<String> usedPermissions = new ArraySet<>();
17553        final int packageCount = su.packages.size();
17554        for (int i = 0; i < packageCount; i++) {
17555            PackageSetting ps = su.packages.valueAt(i);
17556            if (ps.pkg == null) {
17557                continue;
17558            }
17559            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17560            for (int j = 0; j < requestedPermCount; j++) {
17561                String permission = ps.pkg.requestedPermissions.get(j);
17562                BasePermission bp = mSettings.mPermissions.get(permission);
17563                if (bp != null) {
17564                    usedPermissions.add(permission);
17565                }
17566            }
17567        }
17568
17569        PermissionsState permissionsState = su.getPermissionsState();
17570        // Prune install permissions
17571        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17572        final int installPermCount = installPermStates.size();
17573        for (int i = installPermCount - 1; i >= 0;  i--) {
17574            PermissionState permissionState = installPermStates.get(i);
17575            if (!usedPermissions.contains(permissionState.getName())) {
17576                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17577                if (bp != null) {
17578                    permissionsState.revokeInstallPermission(bp);
17579                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17580                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17581                }
17582            }
17583        }
17584
17585        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17586
17587        // Prune runtime permissions
17588        for (int userId : allUserIds) {
17589            List<PermissionState> runtimePermStates = permissionsState
17590                    .getRuntimePermissionStates(userId);
17591            final int runtimePermCount = runtimePermStates.size();
17592            for (int i = runtimePermCount - 1; i >= 0; i--) {
17593                PermissionState permissionState = runtimePermStates.get(i);
17594                if (!usedPermissions.contains(permissionState.getName())) {
17595                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17596                    if (bp != null) {
17597                        permissionsState.revokeRuntimePermission(bp, userId);
17598                        permissionsState.updatePermissionFlags(bp, userId,
17599                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17600                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17601                                runtimePermissionChangedUserIds, userId);
17602                    }
17603                }
17604            }
17605        }
17606
17607        return runtimePermissionChangedUserIds;
17608    }
17609
17610    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17611            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17612        // Update the parent package setting
17613        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17614                res, user, installReason);
17615        // Update the child packages setting
17616        final int childCount = (newPackage.childPackages != null)
17617                ? newPackage.childPackages.size() : 0;
17618        for (int i = 0; i < childCount; i++) {
17619            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17620            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17621            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17622                    childRes.origUsers, childRes, user, installReason);
17623        }
17624    }
17625
17626    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17627            String installerPackageName, int[] allUsers, int[] installedForUsers,
17628            PackageInstalledInfo res, UserHandle user, int installReason) {
17629        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17630
17631        String pkgName = newPackage.packageName;
17632        synchronized (mPackages) {
17633            //write settings. the installStatus will be incomplete at this stage.
17634            //note that the new package setting would have already been
17635            //added to mPackages. It hasn't been persisted yet.
17636            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17637            // TODO: Remove this write? It's also written at the end of this method
17638            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17639            mSettings.writeLPr();
17640            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17641        }
17642
17643        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17644        synchronized (mPackages) {
17645            updatePermissionsLPw(newPackage.packageName, newPackage,
17646                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17647                            ? UPDATE_PERMISSIONS_ALL : 0));
17648            // For system-bundled packages, we assume that installing an upgraded version
17649            // of the package implies that the user actually wants to run that new code,
17650            // so we enable the package.
17651            PackageSetting ps = mSettings.mPackages.get(pkgName);
17652            final int userId = user.getIdentifier();
17653            if (ps != null) {
17654                if (isSystemApp(newPackage)) {
17655                    if (DEBUG_INSTALL) {
17656                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17657                    }
17658                    // Enable system package for requested users
17659                    if (res.origUsers != null) {
17660                        for (int origUserId : res.origUsers) {
17661                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17662                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17663                                        origUserId, installerPackageName);
17664                            }
17665                        }
17666                    }
17667                    // Also convey the prior install/uninstall state
17668                    if (allUsers != null && installedForUsers != null) {
17669                        for (int currentUserId : allUsers) {
17670                            final boolean installed = ArrayUtils.contains(
17671                                    installedForUsers, currentUserId);
17672                            if (DEBUG_INSTALL) {
17673                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17674                            }
17675                            ps.setInstalled(installed, currentUserId);
17676                        }
17677                        // these install state changes will be persisted in the
17678                        // upcoming call to mSettings.writeLPr().
17679                    }
17680                }
17681                // It's implied that when a user requests installation, they want the app to be
17682                // installed and enabled.
17683                if (userId != UserHandle.USER_ALL) {
17684                    ps.setInstalled(true, userId);
17685                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17686                }
17687
17688                // When replacing an existing package, preserve the original install reason for all
17689                // users that had the package installed before.
17690                final Set<Integer> previousUserIds = new ArraySet<>();
17691                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17692                    final int installReasonCount = res.removedInfo.installReasons.size();
17693                    for (int i = 0; i < installReasonCount; i++) {
17694                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17695                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17696                        ps.setInstallReason(previousInstallReason, previousUserId);
17697                        previousUserIds.add(previousUserId);
17698                    }
17699                }
17700
17701                // Set install reason for users that are having the package newly installed.
17702                if (userId == UserHandle.USER_ALL) {
17703                    for (int currentUserId : sUserManager.getUserIds()) {
17704                        if (!previousUserIds.contains(currentUserId)) {
17705                            ps.setInstallReason(installReason, currentUserId);
17706                        }
17707                    }
17708                } else if (!previousUserIds.contains(userId)) {
17709                    ps.setInstallReason(installReason, userId);
17710                }
17711                mSettings.writeKernelMappingLPr(ps);
17712            }
17713            res.name = pkgName;
17714            res.uid = newPackage.applicationInfo.uid;
17715            res.pkg = newPackage;
17716            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17717            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17718            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17719            //to update install status
17720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17721            mSettings.writeLPr();
17722            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17723        }
17724
17725        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17726    }
17727
17728    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17729        try {
17730            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17731            installPackageLI(args, res);
17732        } finally {
17733            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17734        }
17735    }
17736
17737    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17738        final int installFlags = args.installFlags;
17739        final String installerPackageName = args.installerPackageName;
17740        final String volumeUuid = args.volumeUuid;
17741        final File tmpPackageFile = new File(args.getCodePath());
17742        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17743        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17744                || (args.volumeUuid != null));
17745        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17746        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17747        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17748        boolean replace = false;
17749        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17750        if (args.move != null) {
17751            // moving a complete application; perform an initial scan on the new install location
17752            scanFlags |= SCAN_INITIAL;
17753        }
17754        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17755            scanFlags |= SCAN_DONT_KILL_APP;
17756        }
17757        if (instantApp) {
17758            scanFlags |= SCAN_AS_INSTANT_APP;
17759        }
17760        if (fullApp) {
17761            scanFlags |= SCAN_AS_FULL_APP;
17762        }
17763
17764        // Result object to be returned
17765        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17766
17767        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17768
17769        // Sanity check
17770        if (instantApp && (forwardLocked || onExternal)) {
17771            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17772                    + " external=" + onExternal);
17773            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17774            return;
17775        }
17776
17777        // Retrieve PackageSettings and parse package
17778        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17779                | PackageParser.PARSE_ENFORCE_CODE
17780                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17781                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17782                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17783                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17784        PackageParser pp = new PackageParser();
17785        pp.setSeparateProcesses(mSeparateProcesses);
17786        pp.setDisplayMetrics(mMetrics);
17787        pp.setCallback(mPackageParserCallback);
17788
17789        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17790        final PackageParser.Package pkg;
17791        try {
17792            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17793        } catch (PackageParserException e) {
17794            res.setError("Failed parse during installPackageLI", e);
17795            return;
17796        } finally {
17797            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17798        }
17799
17800        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17801        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17802            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17803            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17804                    "Instant app package must target O");
17805            return;
17806        }
17807        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17808            Slog.w(TAG, "Instant app package " + pkg.packageName
17809                    + " does not target targetSandboxVersion 2");
17810            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17811                    "Instant app package must use targetSanboxVersion 2");
17812            return;
17813        }
17814
17815        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17816            // Static shared libraries have synthetic package names
17817            renameStaticSharedLibraryPackage(pkg);
17818
17819            // No static shared libs on external storage
17820            if (onExternal) {
17821                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17822                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17823                        "Packages declaring static-shared libs cannot be updated");
17824                return;
17825            }
17826        }
17827
17828        // If we are installing a clustered package add results for the children
17829        if (pkg.childPackages != null) {
17830            synchronized (mPackages) {
17831                final int childCount = pkg.childPackages.size();
17832                for (int i = 0; i < childCount; i++) {
17833                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17834                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17835                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17836                    childRes.pkg = childPkg;
17837                    childRes.name = childPkg.packageName;
17838                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17839                    if (childPs != null) {
17840                        childRes.origUsers = childPs.queryInstalledUsers(
17841                                sUserManager.getUserIds(), true);
17842                    }
17843                    if ((mPackages.containsKey(childPkg.packageName))) {
17844                        childRes.removedInfo = new PackageRemovedInfo(this);
17845                        childRes.removedInfo.removedPackage = childPkg.packageName;
17846                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17847                    }
17848                    if (res.addedChildPackages == null) {
17849                        res.addedChildPackages = new ArrayMap<>();
17850                    }
17851                    res.addedChildPackages.put(childPkg.packageName, childRes);
17852                }
17853            }
17854        }
17855
17856        // If package doesn't declare API override, mark that we have an install
17857        // time CPU ABI override.
17858        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17859            pkg.cpuAbiOverride = args.abiOverride;
17860        }
17861
17862        String pkgName = res.name = pkg.packageName;
17863        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17864            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17865                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17866                return;
17867            }
17868        }
17869
17870        try {
17871            // either use what we've been given or parse directly from the APK
17872            if (args.certificates != null) {
17873                try {
17874                    PackageParser.populateCertificates(pkg, args.certificates);
17875                } catch (PackageParserException e) {
17876                    // there was something wrong with the certificates we were given;
17877                    // try to pull them from the APK
17878                    PackageParser.collectCertificates(pkg, parseFlags);
17879                }
17880            } else {
17881                PackageParser.collectCertificates(pkg, parseFlags);
17882            }
17883        } catch (PackageParserException e) {
17884            res.setError("Failed collect during installPackageLI", e);
17885            return;
17886        }
17887
17888        // Get rid of all references to package scan path via parser.
17889        pp = null;
17890        String oldCodePath = null;
17891        boolean systemApp = false;
17892        synchronized (mPackages) {
17893            // Check if installing already existing package
17894            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17895                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17896                if (pkg.mOriginalPackages != null
17897                        && pkg.mOriginalPackages.contains(oldName)
17898                        && mPackages.containsKey(oldName)) {
17899                    // This package is derived from an original package,
17900                    // and this device has been updating from that original
17901                    // name.  We must continue using the original name, so
17902                    // rename the new package here.
17903                    pkg.setPackageName(oldName);
17904                    pkgName = pkg.packageName;
17905                    replace = true;
17906                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17907                            + oldName + " pkgName=" + pkgName);
17908                } else if (mPackages.containsKey(pkgName)) {
17909                    // This package, under its official name, already exists
17910                    // on the device; we should replace it.
17911                    replace = true;
17912                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17913                }
17914
17915                // Child packages are installed through the parent package
17916                if (pkg.parentPackage != null) {
17917                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17918                            "Package " + pkg.packageName + " is child of package "
17919                                    + pkg.parentPackage.parentPackage + ". Child packages "
17920                                    + "can be updated only through the parent package.");
17921                    return;
17922                }
17923
17924                if (replace) {
17925                    // Prevent apps opting out from runtime permissions
17926                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17927                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17928                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17929                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17930                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17931                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17932                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17933                                        + " doesn't support runtime permissions but the old"
17934                                        + " target SDK " + oldTargetSdk + " does.");
17935                        return;
17936                    }
17937                    // Prevent apps from downgrading their targetSandbox.
17938                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17939                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17940                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17941                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17942                                "Package " + pkg.packageName + " new target sandbox "
17943                                + newTargetSandbox + " is incompatible with the previous value of"
17944                                + oldTargetSandbox + ".");
17945                        return;
17946                    }
17947
17948                    // Prevent installing of child packages
17949                    if (oldPackage.parentPackage != null) {
17950                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17951                                "Package " + pkg.packageName + " is child of package "
17952                                        + oldPackage.parentPackage + ". Child packages "
17953                                        + "can be updated only through the parent package.");
17954                        return;
17955                    }
17956                }
17957            }
17958
17959            PackageSetting ps = mSettings.mPackages.get(pkgName);
17960            if (ps != null) {
17961                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17962
17963                // Static shared libs have same package with different versions where
17964                // we internally use a synthetic package name to allow multiple versions
17965                // of the same package, therefore we need to compare signatures against
17966                // the package setting for the latest library version.
17967                PackageSetting signatureCheckPs = ps;
17968                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17969                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17970                    if (libraryEntry != null) {
17971                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17972                    }
17973                }
17974
17975                // Quick sanity check that we're signed correctly if updating;
17976                // we'll check this again later when scanning, but we want to
17977                // bail early here before tripping over redefined permissions.
17978                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17979                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17980                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17981                                + pkg.packageName + " upgrade keys do not match the "
17982                                + "previously installed version");
17983                        return;
17984                    }
17985                } else {
17986                    try {
17987                        verifySignaturesLP(signatureCheckPs, pkg);
17988                    } catch (PackageManagerException e) {
17989                        res.setError(e.error, e.getMessage());
17990                        return;
17991                    }
17992                }
17993
17994                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17995                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17996                    systemApp = (ps.pkg.applicationInfo.flags &
17997                            ApplicationInfo.FLAG_SYSTEM) != 0;
17998                }
17999                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18000            }
18001
18002            int N = pkg.permissions.size();
18003            for (int i = N-1; i >= 0; i--) {
18004                PackageParser.Permission perm = pkg.permissions.get(i);
18005                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18006
18007                // Don't allow anyone but the system to define ephemeral permissions.
18008                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18009                        && !systemApp) {
18010                    Slog.w(TAG, "Non-System package " + pkg.packageName
18011                            + " attempting to delcare ephemeral permission "
18012                            + perm.info.name + "; Removing ephemeral.");
18013                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18014                }
18015                // Check whether the newly-scanned package wants to define an already-defined perm
18016                if (bp != null) {
18017                    // If the defining package is signed with our cert, it's okay.  This
18018                    // also includes the "updating the same package" case, of course.
18019                    // "updating same package" could also involve key-rotation.
18020                    final boolean sigsOk;
18021                    if (bp.sourcePackage.equals(pkg.packageName)
18022                            && (bp.packageSetting instanceof PackageSetting)
18023                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18024                                    scanFlags))) {
18025                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18026                    } else {
18027                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18028                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18029                    }
18030                    if (!sigsOk) {
18031                        // If the owning package is the system itself, we log but allow
18032                        // install to proceed; we fail the install on all other permission
18033                        // redefinitions.
18034                        if (!bp.sourcePackage.equals("android")) {
18035                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18036                                    + pkg.packageName + " attempting to redeclare permission "
18037                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18038                            res.origPermission = perm.info.name;
18039                            res.origPackage = bp.sourcePackage;
18040                            return;
18041                        } else {
18042                            Slog.w(TAG, "Package " + pkg.packageName
18043                                    + " attempting to redeclare system permission "
18044                                    + perm.info.name + "; ignoring new declaration");
18045                            pkg.permissions.remove(i);
18046                        }
18047                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18048                        // Prevent apps to change protection level to dangerous from any other
18049                        // type as this would allow a privilege escalation where an app adds a
18050                        // normal/signature permission in other app's group and later redefines
18051                        // it as dangerous leading to the group auto-grant.
18052                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18053                                == PermissionInfo.PROTECTION_DANGEROUS) {
18054                            if (bp != null && !bp.isRuntime()) {
18055                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18056                                        + "non-runtime permission " + perm.info.name
18057                                        + " to runtime; keeping old protection level");
18058                                perm.info.protectionLevel = bp.protectionLevel;
18059                            }
18060                        }
18061                    }
18062                }
18063            }
18064        }
18065
18066        if (systemApp) {
18067            if (onExternal) {
18068                // Abort update; system app can't be replaced with app on sdcard
18069                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18070                        "Cannot install updates to system apps on sdcard");
18071                return;
18072            } else if (instantApp) {
18073                // Abort update; system app can't be replaced with an instant app
18074                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18075                        "Cannot update a system app with an instant app");
18076                return;
18077            }
18078        }
18079
18080        if (args.move != null) {
18081            // We did an in-place move, so dex is ready to roll
18082            scanFlags |= SCAN_NO_DEX;
18083            scanFlags |= SCAN_MOVE;
18084
18085            synchronized (mPackages) {
18086                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18087                if (ps == null) {
18088                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18089                            "Missing settings for moved package " + pkgName);
18090                }
18091
18092                // We moved the entire application as-is, so bring over the
18093                // previously derived ABI information.
18094                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18095                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18096            }
18097
18098        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18099            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18100            scanFlags |= SCAN_NO_DEX;
18101
18102            try {
18103                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18104                    args.abiOverride : pkg.cpuAbiOverride);
18105                final boolean extractNativeLibs = !pkg.isLibrary();
18106                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18107                        extractNativeLibs, mAppLib32InstallDir);
18108            } catch (PackageManagerException pme) {
18109                Slog.e(TAG, "Error deriving application ABI", pme);
18110                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18111                return;
18112            }
18113
18114            // Shared libraries for the package need to be updated.
18115            synchronized (mPackages) {
18116                try {
18117                    updateSharedLibrariesLPr(pkg, null);
18118                } catch (PackageManagerException e) {
18119                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18120                }
18121            }
18122
18123            // dexopt can take some time to complete, so, for instant apps, we skip this
18124            // step during installation. Instead, we'll take extra time the first time the
18125            // instant app starts. It's preferred to do it this way to provide continuous
18126            // progress to the user instead of mysteriously blocking somewhere in the
18127            // middle of running an instant app. The default behaviour can be overridden
18128            // via gservices.
18129            if (!instantApp || Global.getInt(
18130                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18131                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18132                // Do not run PackageDexOptimizer through the local performDexOpt
18133                // method because `pkg` may not be in `mPackages` yet.
18134                //
18135                // Also, don't fail application installs if the dexopt step fails.
18136                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18137                        null /* instructionSets */, false /* checkProfiles */,
18138                        getCompilerFilterForReason(REASON_INSTALL),
18139                        getOrCreateCompilerPackageStats(pkg),
18140                        mDexManager.isUsedByOtherApps(pkg.packageName));
18141                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18142            }
18143
18144            // Notify BackgroundDexOptService that the package has been changed.
18145            // If this is an update of a package which used to fail to compile,
18146            // BDOS will remove it from its blacklist.
18147            // TODO: Layering violation
18148            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18149        }
18150
18151        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18152            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18153            return;
18154        }
18155
18156        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18157
18158        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18159                "installPackageLI")) {
18160            if (replace) {
18161                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18162                    // Static libs have a synthetic package name containing the version
18163                    // and cannot be updated as an update would get a new package name,
18164                    // unless this is the exact same version code which is useful for
18165                    // development.
18166                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18167                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18168                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18169                                + "static-shared libs cannot be updated");
18170                        return;
18171                    }
18172                }
18173                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18174                        installerPackageName, res, args.installReason);
18175            } else {
18176                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18177                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18178            }
18179        }
18180
18181        synchronized (mPackages) {
18182            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18183            if (ps != null) {
18184                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18185                ps.setUpdateAvailable(false /*updateAvailable*/);
18186            }
18187
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                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18192                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18193                if (childPs != null) {
18194                    childRes.newUsers = childPs.queryInstalledUsers(
18195                            sUserManager.getUserIds(), true);
18196                }
18197            }
18198
18199            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18200                updateSequenceNumberLP(ps, res.newUsers);
18201                updateInstantAppInstallerLocked(pkgName);
18202            }
18203        }
18204    }
18205
18206    private void startIntentFilterVerifications(int userId, boolean replacing,
18207            PackageParser.Package pkg) {
18208        if (mIntentFilterVerifierComponent == null) {
18209            Slog.w(TAG, "No IntentFilter verification will not be done as "
18210                    + "there is no IntentFilterVerifier available!");
18211            return;
18212        }
18213
18214        final int verifierUid = getPackageUid(
18215                mIntentFilterVerifierComponent.getPackageName(),
18216                MATCH_DEBUG_TRIAGED_MISSING,
18217                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18218
18219        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18220        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18221        mHandler.sendMessage(msg);
18222
18223        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18224        for (int i = 0; i < childCount; i++) {
18225            PackageParser.Package childPkg = pkg.childPackages.get(i);
18226            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18227            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18228            mHandler.sendMessage(msg);
18229        }
18230    }
18231
18232    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18233            PackageParser.Package pkg) {
18234        int size = pkg.activities.size();
18235        if (size == 0) {
18236            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18237                    "No activity, so no need to verify any IntentFilter!");
18238            return;
18239        }
18240
18241        final boolean hasDomainURLs = hasDomainURLs(pkg);
18242        if (!hasDomainURLs) {
18243            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18244                    "No domain URLs, so no need to verify any IntentFilter!");
18245            return;
18246        }
18247
18248        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18249                + " if any IntentFilter from the " + size
18250                + " Activities needs verification ...");
18251
18252        int count = 0;
18253        final String packageName = pkg.packageName;
18254
18255        synchronized (mPackages) {
18256            // If this is a new install and we see that we've already run verification for this
18257            // package, we have nothing to do: it means the state was restored from backup.
18258            if (!replacing) {
18259                IntentFilterVerificationInfo ivi =
18260                        mSettings.getIntentFilterVerificationLPr(packageName);
18261                if (ivi != null) {
18262                    if (DEBUG_DOMAIN_VERIFICATION) {
18263                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18264                                + ivi.getStatusString());
18265                    }
18266                    return;
18267                }
18268            }
18269
18270            // If any filters need to be verified, then all need to be.
18271            boolean needToVerify = false;
18272            for (PackageParser.Activity a : pkg.activities) {
18273                for (ActivityIntentInfo filter : a.intents) {
18274                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18275                        if (DEBUG_DOMAIN_VERIFICATION) {
18276                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18277                        }
18278                        needToVerify = true;
18279                        break;
18280                    }
18281                }
18282            }
18283
18284            if (needToVerify) {
18285                final int verificationId = mIntentFilterVerificationToken++;
18286                for (PackageParser.Activity a : pkg.activities) {
18287                    for (ActivityIntentInfo filter : a.intents) {
18288                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18289                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18290                                    "Verification needed for IntentFilter:" + filter.toString());
18291                            mIntentFilterVerifier.addOneIntentFilterVerification(
18292                                    verifierUid, userId, verificationId, filter, packageName);
18293                            count++;
18294                        }
18295                    }
18296                }
18297            }
18298        }
18299
18300        if (count > 0) {
18301            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18302                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18303                    +  " for userId:" + userId);
18304            mIntentFilterVerifier.startVerifications(userId);
18305        } else {
18306            if (DEBUG_DOMAIN_VERIFICATION) {
18307                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18308            }
18309        }
18310    }
18311
18312    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18313        final ComponentName cn  = filter.activity.getComponentName();
18314        final String packageName = cn.getPackageName();
18315
18316        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18317                packageName);
18318        if (ivi == null) {
18319            return true;
18320        }
18321        int status = ivi.getStatus();
18322        switch (status) {
18323            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18324            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18325                return true;
18326
18327            default:
18328                // Nothing to do
18329                return false;
18330        }
18331    }
18332
18333    private static boolean isMultiArch(ApplicationInfo info) {
18334        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18335    }
18336
18337    private static boolean isExternal(PackageParser.Package pkg) {
18338        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18339    }
18340
18341    private static boolean isExternal(PackageSetting ps) {
18342        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18343    }
18344
18345    private static boolean isSystemApp(PackageParser.Package pkg) {
18346        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18347    }
18348
18349    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18350        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18351    }
18352
18353    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18354        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18355    }
18356
18357    private static boolean isSystemApp(PackageSetting ps) {
18358        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18359    }
18360
18361    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18362        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18363    }
18364
18365    private int packageFlagsToInstallFlags(PackageSetting ps) {
18366        int installFlags = 0;
18367        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18368            // This existing package was an external ASEC install when we have
18369            // the external flag without a UUID
18370            installFlags |= PackageManager.INSTALL_EXTERNAL;
18371        }
18372        if (ps.isForwardLocked()) {
18373            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18374        }
18375        return installFlags;
18376    }
18377
18378    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18379        if (isExternal(pkg)) {
18380            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18381                return StorageManager.UUID_PRIMARY_PHYSICAL;
18382            } else {
18383                return pkg.volumeUuid;
18384            }
18385        } else {
18386            return StorageManager.UUID_PRIVATE_INTERNAL;
18387        }
18388    }
18389
18390    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18391        if (isExternal(pkg)) {
18392            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18393                return mSettings.getExternalVersion();
18394            } else {
18395                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18396            }
18397        } else {
18398            return mSettings.getInternalVersion();
18399        }
18400    }
18401
18402    private void deleteTempPackageFiles() {
18403        final FilenameFilter filter = new FilenameFilter() {
18404            public boolean accept(File dir, String name) {
18405                return name.startsWith("vmdl") && name.endsWith(".tmp");
18406            }
18407        };
18408        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18409            file.delete();
18410        }
18411    }
18412
18413    @Override
18414    public void deletePackageAsUser(String packageName, int versionCode,
18415            IPackageDeleteObserver observer, int userId, int flags) {
18416        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18417                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18418    }
18419
18420    @Override
18421    public void deletePackageVersioned(VersionedPackage versionedPackage,
18422            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18423        final int callingUid = Binder.getCallingUid();
18424        mContext.enforceCallingOrSelfPermission(
18425                android.Manifest.permission.DELETE_PACKAGES, null);
18426        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18427        Preconditions.checkNotNull(versionedPackage);
18428        Preconditions.checkNotNull(observer);
18429        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18430                PackageManager.VERSION_CODE_HIGHEST,
18431                Integer.MAX_VALUE, "versionCode must be >= -1");
18432
18433        final String packageName = versionedPackage.getPackageName();
18434        final int versionCode = versionedPackage.getVersionCode();
18435        final String internalPackageName;
18436        synchronized (mPackages) {
18437            // Normalize package name to handle renamed packages and static libs
18438            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18439                    versionedPackage.getVersionCode());
18440        }
18441
18442        final int uid = Binder.getCallingUid();
18443        if (!isOrphaned(internalPackageName)
18444                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18445            try {
18446                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18447                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18448                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18449                observer.onUserActionRequired(intent);
18450            } catch (RemoteException re) {
18451            }
18452            return;
18453        }
18454        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18455        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18456        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18457            mContext.enforceCallingOrSelfPermission(
18458                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18459                    "deletePackage for user " + userId);
18460        }
18461
18462        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18463            try {
18464                observer.onPackageDeleted(packageName,
18465                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18466            } catch (RemoteException re) {
18467            }
18468            return;
18469        }
18470
18471        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18472            try {
18473                observer.onPackageDeleted(packageName,
18474                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18475            } catch (RemoteException re) {
18476            }
18477            return;
18478        }
18479
18480        if (DEBUG_REMOVE) {
18481            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18482                    + " deleteAllUsers: " + deleteAllUsers + " version="
18483                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18484                    ? "VERSION_CODE_HIGHEST" : versionCode));
18485        }
18486        // Queue up an async operation since the package deletion may take a little while.
18487        mHandler.post(new Runnable() {
18488            public void run() {
18489                mHandler.removeCallbacks(this);
18490                int returnCode;
18491                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18492                boolean doDeletePackage = true;
18493                if (ps != null) {
18494                    final boolean targetIsInstantApp =
18495                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18496                    doDeletePackage = !targetIsInstantApp
18497                            || canViewInstantApps;
18498                }
18499                if (doDeletePackage) {
18500                    if (!deleteAllUsers) {
18501                        returnCode = deletePackageX(internalPackageName, versionCode,
18502                                userId, deleteFlags);
18503                    } else {
18504                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18505                                internalPackageName, users);
18506                        // If nobody is blocking uninstall, proceed with delete for all users
18507                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18508                            returnCode = deletePackageX(internalPackageName, versionCode,
18509                                    userId, deleteFlags);
18510                        } else {
18511                            // Otherwise uninstall individually for users with blockUninstalls=false
18512                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18513                            for (int userId : users) {
18514                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18515                                    returnCode = deletePackageX(internalPackageName, versionCode,
18516                                            userId, userFlags);
18517                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18518                                        Slog.w(TAG, "Package delete failed for user " + userId
18519                                                + ", returnCode " + returnCode);
18520                                    }
18521                                }
18522                            }
18523                            // The app has only been marked uninstalled for certain users.
18524                            // We still need to report that delete was blocked
18525                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18526                        }
18527                    }
18528                } else {
18529                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18530                }
18531                try {
18532                    observer.onPackageDeleted(packageName, returnCode, null);
18533                } catch (RemoteException e) {
18534                    Log.i(TAG, "Observer no longer exists.");
18535                } //end catch
18536            } //end run
18537        });
18538    }
18539
18540    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18541        if (pkg.staticSharedLibName != null) {
18542            return pkg.manifestPackageName;
18543        }
18544        return pkg.packageName;
18545    }
18546
18547    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18548        // Handle renamed packages
18549        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18550        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18551
18552        // Is this a static library?
18553        SparseArray<SharedLibraryEntry> versionedLib =
18554                mStaticLibsByDeclaringPackage.get(packageName);
18555        if (versionedLib == null || versionedLib.size() <= 0) {
18556            return packageName;
18557        }
18558
18559        // Figure out which lib versions the caller can see
18560        SparseIntArray versionsCallerCanSee = null;
18561        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18562        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18563                && callingAppId != Process.ROOT_UID) {
18564            versionsCallerCanSee = new SparseIntArray();
18565            String libName = versionedLib.valueAt(0).info.getName();
18566            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18567            if (uidPackages != null) {
18568                for (String uidPackage : uidPackages) {
18569                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18570                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18571                    if (libIdx >= 0) {
18572                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18573                        versionsCallerCanSee.append(libVersion, libVersion);
18574                    }
18575                }
18576            }
18577        }
18578
18579        // Caller can see nothing - done
18580        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18581            return packageName;
18582        }
18583
18584        // Find the version the caller can see and the app version code
18585        SharedLibraryEntry highestVersion = null;
18586        final int versionCount = versionedLib.size();
18587        for (int i = 0; i < versionCount; i++) {
18588            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18589            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18590                    libEntry.info.getVersion()) < 0) {
18591                continue;
18592            }
18593            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18594            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18595                if (libVersionCode == versionCode) {
18596                    return libEntry.apk;
18597                }
18598            } else if (highestVersion == null) {
18599                highestVersion = libEntry;
18600            } else if (libVersionCode  > highestVersion.info
18601                    .getDeclaringPackage().getVersionCode()) {
18602                highestVersion = libEntry;
18603            }
18604        }
18605
18606        if (highestVersion != null) {
18607            return highestVersion.apk;
18608        }
18609
18610        return packageName;
18611    }
18612
18613    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18614        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18615              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18616            return true;
18617        }
18618        final int callingUserId = UserHandle.getUserId(callingUid);
18619        // If the caller installed the pkgName, then allow it to silently uninstall.
18620        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18621            return true;
18622        }
18623
18624        // Allow package verifier to silently uninstall.
18625        if (mRequiredVerifierPackage != null &&
18626                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18627            return true;
18628        }
18629
18630        // Allow package uninstaller to silently uninstall.
18631        if (mRequiredUninstallerPackage != null &&
18632                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18633            return true;
18634        }
18635
18636        // Allow storage manager to silently uninstall.
18637        if (mStorageManagerPackage != null &&
18638                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18639            return true;
18640        }
18641        return false;
18642    }
18643
18644    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18645        int[] result = EMPTY_INT_ARRAY;
18646        for (int userId : userIds) {
18647            if (getBlockUninstallForUser(packageName, userId)) {
18648                result = ArrayUtils.appendInt(result, userId);
18649            }
18650        }
18651        return result;
18652    }
18653
18654    @Override
18655    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18656        final int callingUid = Binder.getCallingUid();
18657        if (getInstantAppPackageName(callingUid) != null
18658                && !isCallerSameApp(packageName, callingUid)) {
18659            return false;
18660        }
18661        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18662    }
18663
18664    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18665        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18666                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18667        try {
18668            if (dpm != null) {
18669                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18670                        /* callingUserOnly =*/ false);
18671                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18672                        : deviceOwnerComponentName.getPackageName();
18673                // Does the package contains the device owner?
18674                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18675                // this check is probably not needed, since DO should be registered as a device
18676                // admin on some user too. (Original bug for this: b/17657954)
18677                if (packageName.equals(deviceOwnerPackageName)) {
18678                    return true;
18679                }
18680                // Does it contain a device admin for any user?
18681                int[] users;
18682                if (userId == UserHandle.USER_ALL) {
18683                    users = sUserManager.getUserIds();
18684                } else {
18685                    users = new int[]{userId};
18686                }
18687                for (int i = 0; i < users.length; ++i) {
18688                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18689                        return true;
18690                    }
18691                }
18692            }
18693        } catch (RemoteException e) {
18694        }
18695        return false;
18696    }
18697
18698    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18699        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18700    }
18701
18702    /**
18703     *  This method is an internal method that could be get invoked either
18704     *  to delete an installed package or to clean up a failed installation.
18705     *  After deleting an installed package, a broadcast is sent to notify any
18706     *  listeners that the package has been removed. For cleaning up a failed
18707     *  installation, the broadcast is not necessary since the package's
18708     *  installation wouldn't have sent the initial broadcast either
18709     *  The key steps in deleting a package are
18710     *  deleting the package information in internal structures like mPackages,
18711     *  deleting the packages base directories through installd
18712     *  updating mSettings to reflect current status
18713     *  persisting settings for later use
18714     *  sending a broadcast if necessary
18715     */
18716    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18717        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18718        final boolean res;
18719
18720        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18721                ? UserHandle.USER_ALL : userId;
18722
18723        if (isPackageDeviceAdmin(packageName, removeUser)) {
18724            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18725            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18726        }
18727
18728        PackageSetting uninstalledPs = null;
18729        PackageParser.Package pkg = null;
18730
18731        // for the uninstall-updates case and restricted profiles, remember the per-
18732        // user handle installed state
18733        int[] allUsers;
18734        synchronized (mPackages) {
18735            uninstalledPs = mSettings.mPackages.get(packageName);
18736            if (uninstalledPs == null) {
18737                Slog.w(TAG, "Not removing non-existent package " + packageName);
18738                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18739            }
18740
18741            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18742                    && uninstalledPs.versionCode != versionCode) {
18743                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18744                        + uninstalledPs.versionCode + " != " + versionCode);
18745                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18746            }
18747
18748            // Static shared libs can be declared by any package, so let us not
18749            // allow removing a package if it provides a lib others depend on.
18750            pkg = mPackages.get(packageName);
18751
18752            allUsers = sUserManager.getUserIds();
18753
18754            if (pkg != null && pkg.staticSharedLibName != null) {
18755                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18756                        pkg.staticSharedLibVersion);
18757                if (libEntry != null) {
18758                    for (int currUserId : allUsers) {
18759                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18760                            continue;
18761                        }
18762                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18763                                libEntry.info, 0, currUserId);
18764                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18765                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18766                                    + " hosting lib " + libEntry.info.getName() + " version "
18767                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18768                                    + " for user " + currUserId);
18769                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18770                        }
18771                    }
18772                }
18773            }
18774
18775            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18776        }
18777
18778        final int freezeUser;
18779        if (isUpdatedSystemApp(uninstalledPs)
18780                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18781            // We're downgrading a system app, which will apply to all users, so
18782            // freeze them all during the downgrade
18783            freezeUser = UserHandle.USER_ALL;
18784        } else {
18785            freezeUser = removeUser;
18786        }
18787
18788        synchronized (mInstallLock) {
18789            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18790            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18791                    deleteFlags, "deletePackageX")) {
18792                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18793                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18794            }
18795            synchronized (mPackages) {
18796                if (res) {
18797                    if (pkg != null) {
18798                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18799                    }
18800                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18801                    updateInstantAppInstallerLocked(packageName);
18802                }
18803            }
18804        }
18805
18806        if (res) {
18807            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18808            info.sendPackageRemovedBroadcasts(killApp);
18809            info.sendSystemPackageUpdatedBroadcasts();
18810            info.sendSystemPackageAppearedBroadcasts();
18811        }
18812        // Force a gc here.
18813        Runtime.getRuntime().gc();
18814        // Delete the resources here after sending the broadcast to let
18815        // other processes clean up before deleting resources.
18816        if (info.args != null) {
18817            synchronized (mInstallLock) {
18818                info.args.doPostDeleteLI(true);
18819            }
18820        }
18821
18822        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18823    }
18824
18825    static class PackageRemovedInfo {
18826        final PackageSender packageSender;
18827        String removedPackage;
18828        String installerPackageName;
18829        int uid = -1;
18830        int removedAppId = -1;
18831        int[] origUsers;
18832        int[] removedUsers = null;
18833        int[] broadcastUsers = null;
18834        SparseArray<Integer> installReasons;
18835        boolean isRemovedPackageSystemUpdate = false;
18836        boolean isUpdate;
18837        boolean dataRemoved;
18838        boolean removedForAllUsers;
18839        boolean isStaticSharedLib;
18840        // Clean up resources deleted packages.
18841        InstallArgs args = null;
18842        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18843        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18844
18845        PackageRemovedInfo(PackageSender packageSender) {
18846            this.packageSender = packageSender;
18847        }
18848
18849        void sendPackageRemovedBroadcasts(boolean killApp) {
18850            sendPackageRemovedBroadcastInternal(killApp);
18851            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18852            for (int i = 0; i < childCount; i++) {
18853                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18854                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18855            }
18856        }
18857
18858        void sendSystemPackageUpdatedBroadcasts() {
18859            if (isRemovedPackageSystemUpdate) {
18860                sendSystemPackageUpdatedBroadcastsInternal();
18861                final int childCount = (removedChildPackages != null)
18862                        ? removedChildPackages.size() : 0;
18863                for (int i = 0; i < childCount; i++) {
18864                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18865                    if (childInfo.isRemovedPackageSystemUpdate) {
18866                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18867                    }
18868                }
18869            }
18870        }
18871
18872        void sendSystemPackageAppearedBroadcasts() {
18873            final int packageCount = (appearedChildPackages != null)
18874                    ? appearedChildPackages.size() : 0;
18875            for (int i = 0; i < packageCount; i++) {
18876                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18877                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18878                    true, UserHandle.getAppId(installedInfo.uid),
18879                    installedInfo.newUsers);
18880            }
18881        }
18882
18883        private void sendSystemPackageUpdatedBroadcastsInternal() {
18884            Bundle extras = new Bundle(2);
18885            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18886            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18887            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18888                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18889            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18890                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18891            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18892                null, null, 0, removedPackage, null, null);
18893            if (installerPackageName != null) {
18894                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18895                        removedPackage, extras, 0 /*flags*/,
18896                        installerPackageName, null, null);
18897                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18898                        removedPackage, extras, 0 /*flags*/,
18899                        installerPackageName, null, null);
18900            }
18901        }
18902
18903        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18904            // Don't send static shared library removal broadcasts as these
18905            // libs are visible only the the apps that depend on them an one
18906            // cannot remove the library if it has a dependency.
18907            if (isStaticSharedLib) {
18908                return;
18909            }
18910            Bundle extras = new Bundle(2);
18911            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18912            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18913            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18914            if (isUpdate || isRemovedPackageSystemUpdate) {
18915                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18916            }
18917            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18918            if (removedPackage != null) {
18919                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18920                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18921                if (installerPackageName != null) {
18922                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18923                            removedPackage, extras, 0 /*flags*/,
18924                            installerPackageName, null, broadcastUsers);
18925                }
18926                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18927                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18928                        removedPackage, extras,
18929                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18930                        null, null, broadcastUsers);
18931                }
18932            }
18933            if (removedAppId >= 0) {
18934                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18935                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18936            }
18937        }
18938
18939        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18940            removedUsers = userIds;
18941            if (removedUsers == null) {
18942                broadcastUsers = null;
18943                return;
18944            }
18945
18946            broadcastUsers = EMPTY_INT_ARRAY;
18947            for (int i = userIds.length - 1; i >= 0; --i) {
18948                final int userId = userIds[i];
18949                if (deletedPackageSetting.getInstantApp(userId)) {
18950                    continue;
18951                }
18952                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18953            }
18954        }
18955    }
18956
18957    /*
18958     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18959     * flag is not set, the data directory is removed as well.
18960     * make sure this flag is set for partially installed apps. If not its meaningless to
18961     * delete a partially installed application.
18962     */
18963    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18964            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18965        String packageName = ps.name;
18966        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18967        // Retrieve object to delete permissions for shared user later on
18968        final PackageParser.Package deletedPkg;
18969        final PackageSetting deletedPs;
18970        // reader
18971        synchronized (mPackages) {
18972            deletedPkg = mPackages.get(packageName);
18973            deletedPs = mSettings.mPackages.get(packageName);
18974            if (outInfo != null) {
18975                outInfo.removedPackage = packageName;
18976                outInfo.installerPackageName = ps.installerPackageName;
18977                outInfo.isStaticSharedLib = deletedPkg != null
18978                        && deletedPkg.staticSharedLibName != null;
18979                outInfo.populateUsers(deletedPs == null ? null
18980                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18981            }
18982        }
18983
18984        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18985
18986        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18987            final PackageParser.Package resolvedPkg;
18988            if (deletedPkg != null) {
18989                resolvedPkg = deletedPkg;
18990            } else {
18991                // We don't have a parsed package when it lives on an ejected
18992                // adopted storage device, so fake something together
18993                resolvedPkg = new PackageParser.Package(ps.name);
18994                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18995            }
18996            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18997                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18998            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18999            if (outInfo != null) {
19000                outInfo.dataRemoved = true;
19001            }
19002            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19003        }
19004
19005        int removedAppId = -1;
19006
19007        // writer
19008        synchronized (mPackages) {
19009            boolean installedStateChanged = false;
19010            if (deletedPs != null) {
19011                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19012                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19013                    clearDefaultBrowserIfNeeded(packageName);
19014                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19015                    removedAppId = mSettings.removePackageLPw(packageName);
19016                    if (outInfo != null) {
19017                        outInfo.removedAppId = removedAppId;
19018                    }
19019                    updatePermissionsLPw(deletedPs.name, null, 0);
19020                    if (deletedPs.sharedUser != null) {
19021                        // Remove permissions associated with package. Since runtime
19022                        // permissions are per user we have to kill the removed package
19023                        // or packages running under the shared user of the removed
19024                        // package if revoking the permissions requested only by the removed
19025                        // package is successful and this causes a change in gids.
19026                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19027                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19028                                    userId);
19029                            if (userIdToKill == UserHandle.USER_ALL
19030                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19031                                // If gids changed for this user, kill all affected packages.
19032                                mHandler.post(new Runnable() {
19033                                    @Override
19034                                    public void run() {
19035                                        // This has to happen with no lock held.
19036                                        killApplication(deletedPs.name, deletedPs.appId,
19037                                                KILL_APP_REASON_GIDS_CHANGED);
19038                                    }
19039                                });
19040                                break;
19041                            }
19042                        }
19043                    }
19044                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19045                }
19046                // make sure to preserve per-user disabled state if this removal was just
19047                // a downgrade of a system app to the factory package
19048                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19049                    if (DEBUG_REMOVE) {
19050                        Slog.d(TAG, "Propagating install state across downgrade");
19051                    }
19052                    for (int userId : allUserHandles) {
19053                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19054                        if (DEBUG_REMOVE) {
19055                            Slog.d(TAG, "    user " + userId + " => " + installed);
19056                        }
19057                        if (installed != ps.getInstalled(userId)) {
19058                            installedStateChanged = true;
19059                        }
19060                        ps.setInstalled(installed, userId);
19061                    }
19062                }
19063            }
19064            // can downgrade to reader
19065            if (writeSettings) {
19066                // Save settings now
19067                mSettings.writeLPr();
19068            }
19069            if (installedStateChanged) {
19070                mSettings.writeKernelMappingLPr(ps);
19071            }
19072        }
19073        if (removedAppId != -1) {
19074            // A user ID was deleted here. Go through all users and remove it
19075            // from KeyStore.
19076            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19077        }
19078    }
19079
19080    static boolean locationIsPrivileged(File path) {
19081        try {
19082            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19083                    .getCanonicalPath();
19084            return path.getCanonicalPath().startsWith(privilegedAppDir);
19085        } catch (IOException e) {
19086            Slog.e(TAG, "Unable to access code path " + path);
19087        }
19088        return false;
19089    }
19090
19091    /*
19092     * Tries to delete system package.
19093     */
19094    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19095            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19096            boolean writeSettings) {
19097        if (deletedPs.parentPackageName != null) {
19098            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19099            return false;
19100        }
19101
19102        final boolean applyUserRestrictions
19103                = (allUserHandles != null) && (outInfo.origUsers != null);
19104        final PackageSetting disabledPs;
19105        // Confirm if the system package has been updated
19106        // An updated system app can be deleted. This will also have to restore
19107        // the system pkg from system partition
19108        // reader
19109        synchronized (mPackages) {
19110            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19111        }
19112
19113        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19114                + " disabledPs=" + disabledPs);
19115
19116        if (disabledPs == null) {
19117            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19118            return false;
19119        } else if (DEBUG_REMOVE) {
19120            Slog.d(TAG, "Deleting system pkg from data partition");
19121        }
19122
19123        if (DEBUG_REMOVE) {
19124            if (applyUserRestrictions) {
19125                Slog.d(TAG, "Remembering install states:");
19126                for (int userId : allUserHandles) {
19127                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19128                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19129                }
19130            }
19131        }
19132
19133        // Delete the updated package
19134        outInfo.isRemovedPackageSystemUpdate = true;
19135        if (outInfo.removedChildPackages != null) {
19136            final int childCount = (deletedPs.childPackageNames != null)
19137                    ? deletedPs.childPackageNames.size() : 0;
19138            for (int i = 0; i < childCount; i++) {
19139                String childPackageName = deletedPs.childPackageNames.get(i);
19140                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19141                        .contains(childPackageName)) {
19142                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19143                            childPackageName);
19144                    if (childInfo != null) {
19145                        childInfo.isRemovedPackageSystemUpdate = true;
19146                    }
19147                }
19148            }
19149        }
19150
19151        if (disabledPs.versionCode < deletedPs.versionCode) {
19152            // Delete data for downgrades
19153            flags &= ~PackageManager.DELETE_KEEP_DATA;
19154        } else {
19155            // Preserve data by setting flag
19156            flags |= PackageManager.DELETE_KEEP_DATA;
19157        }
19158
19159        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19160                outInfo, writeSettings, disabledPs.pkg);
19161        if (!ret) {
19162            return false;
19163        }
19164
19165        // writer
19166        synchronized (mPackages) {
19167            // Reinstate the old system package
19168            enableSystemPackageLPw(disabledPs.pkg);
19169            // Remove any native libraries from the upgraded package.
19170            removeNativeBinariesLI(deletedPs);
19171        }
19172
19173        // Install the system package
19174        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19175        int parseFlags = mDefParseFlags
19176                | PackageParser.PARSE_MUST_BE_APK
19177                | PackageParser.PARSE_IS_SYSTEM
19178                | PackageParser.PARSE_IS_SYSTEM_DIR;
19179        if (locationIsPrivileged(disabledPs.codePath)) {
19180            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19181        }
19182
19183        final PackageParser.Package newPkg;
19184        try {
19185            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19186                0 /* currentTime */, null);
19187        } catch (PackageManagerException e) {
19188            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19189                    + e.getMessage());
19190            return false;
19191        }
19192
19193        try {
19194            // update shared libraries for the newly re-installed system package
19195            updateSharedLibrariesLPr(newPkg, null);
19196        } catch (PackageManagerException e) {
19197            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19198        }
19199
19200        prepareAppDataAfterInstallLIF(newPkg);
19201
19202        // writer
19203        synchronized (mPackages) {
19204            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19205
19206            // Propagate the permissions state as we do not want to drop on the floor
19207            // runtime permissions. The update permissions method below will take
19208            // care of removing obsolete permissions and grant install permissions.
19209            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19210            updatePermissionsLPw(newPkg.packageName, newPkg,
19211                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19212
19213            if (applyUserRestrictions) {
19214                boolean installedStateChanged = false;
19215                if (DEBUG_REMOVE) {
19216                    Slog.d(TAG, "Propagating install state across reinstall");
19217                }
19218                for (int userId : allUserHandles) {
19219                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19220                    if (DEBUG_REMOVE) {
19221                        Slog.d(TAG, "    user " + userId + " => " + installed);
19222                    }
19223                    if (installed != ps.getInstalled(userId)) {
19224                        installedStateChanged = true;
19225                    }
19226                    ps.setInstalled(installed, userId);
19227
19228                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19229                }
19230                // Regardless of writeSettings we need to ensure that this restriction
19231                // state propagation is persisted
19232                mSettings.writeAllUsersPackageRestrictionsLPr();
19233                if (installedStateChanged) {
19234                    mSettings.writeKernelMappingLPr(ps);
19235                }
19236            }
19237            // can downgrade to reader here
19238            if (writeSettings) {
19239                mSettings.writeLPr();
19240            }
19241        }
19242        return true;
19243    }
19244
19245    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19246            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19247            PackageRemovedInfo outInfo, boolean writeSettings,
19248            PackageParser.Package replacingPackage) {
19249        synchronized (mPackages) {
19250            if (outInfo != null) {
19251                outInfo.uid = ps.appId;
19252            }
19253
19254            if (outInfo != null && outInfo.removedChildPackages != null) {
19255                final int childCount = (ps.childPackageNames != null)
19256                        ? ps.childPackageNames.size() : 0;
19257                for (int i = 0; i < childCount; i++) {
19258                    String childPackageName = ps.childPackageNames.get(i);
19259                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19260                    if (childPs == null) {
19261                        return false;
19262                    }
19263                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19264                            childPackageName);
19265                    if (childInfo != null) {
19266                        childInfo.uid = childPs.appId;
19267                    }
19268                }
19269            }
19270        }
19271
19272        // Delete package data from internal structures and also remove data if flag is set
19273        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19274
19275        // Delete the child packages data
19276        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19277        for (int i = 0; i < childCount; i++) {
19278            PackageSetting childPs;
19279            synchronized (mPackages) {
19280                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19281            }
19282            if (childPs != null) {
19283                PackageRemovedInfo childOutInfo = (outInfo != null
19284                        && outInfo.removedChildPackages != null)
19285                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19286                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19287                        && (replacingPackage != null
19288                        && !replacingPackage.hasChildPackage(childPs.name))
19289                        ? flags & ~DELETE_KEEP_DATA : flags;
19290                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19291                        deleteFlags, writeSettings);
19292            }
19293        }
19294
19295        // Delete application code and resources only for parent packages
19296        if (ps.parentPackageName == null) {
19297            if (deleteCodeAndResources && (outInfo != null)) {
19298                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19299                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19300                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19301            }
19302        }
19303
19304        return true;
19305    }
19306
19307    @Override
19308    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19309            int userId) {
19310        mContext.enforceCallingOrSelfPermission(
19311                android.Manifest.permission.DELETE_PACKAGES, null);
19312        synchronized (mPackages) {
19313            // Cannot block uninstall of static shared libs as they are
19314            // considered a part of the using app (emulating static linking).
19315            // Also static libs are installed always on internal storage.
19316            PackageParser.Package pkg = mPackages.get(packageName);
19317            if (pkg != null && pkg.staticSharedLibName != null) {
19318                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19319                        + " providing static shared library: " + pkg.staticSharedLibName);
19320                return false;
19321            }
19322            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19323            mSettings.writePackageRestrictionsLPr(userId);
19324        }
19325        return true;
19326    }
19327
19328    @Override
19329    public boolean getBlockUninstallForUser(String packageName, int userId) {
19330        synchronized (mPackages) {
19331            final PackageSetting ps = mSettings.mPackages.get(packageName);
19332            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19333                return false;
19334            }
19335            return mSettings.getBlockUninstallLPr(userId, packageName);
19336        }
19337    }
19338
19339    @Override
19340    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19341        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19342        synchronized (mPackages) {
19343            PackageSetting ps = mSettings.mPackages.get(packageName);
19344            if (ps == null) {
19345                Log.w(TAG, "Package doesn't exist: " + packageName);
19346                return false;
19347            }
19348            if (systemUserApp) {
19349                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19350            } else {
19351                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19352            }
19353            mSettings.writeLPr();
19354        }
19355        return true;
19356    }
19357
19358    /*
19359     * This method handles package deletion in general
19360     */
19361    private boolean deletePackageLIF(String packageName, UserHandle user,
19362            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19363            PackageRemovedInfo outInfo, boolean writeSettings,
19364            PackageParser.Package replacingPackage) {
19365        if (packageName == null) {
19366            Slog.w(TAG, "Attempt to delete null packageName.");
19367            return false;
19368        }
19369
19370        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19371
19372        PackageSetting ps;
19373        synchronized (mPackages) {
19374            ps = mSettings.mPackages.get(packageName);
19375            if (ps == null) {
19376                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19377                return false;
19378            }
19379
19380            if (ps.parentPackageName != null && (!isSystemApp(ps)
19381                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19382                if (DEBUG_REMOVE) {
19383                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19384                            + ((user == null) ? UserHandle.USER_ALL : user));
19385                }
19386                final int removedUserId = (user != null) ? user.getIdentifier()
19387                        : UserHandle.USER_ALL;
19388                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19389                    return false;
19390                }
19391                markPackageUninstalledForUserLPw(ps, user);
19392                scheduleWritePackageRestrictionsLocked(user);
19393                return true;
19394            }
19395        }
19396
19397        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19398                && user.getIdentifier() != UserHandle.USER_ALL)) {
19399            // The caller is asking that the package only be deleted for a single
19400            // user.  To do this, we just mark its uninstalled state and delete
19401            // its data. If this is a system app, we only allow this to happen if
19402            // they have set the special DELETE_SYSTEM_APP which requests different
19403            // semantics than normal for uninstalling system apps.
19404            markPackageUninstalledForUserLPw(ps, user);
19405
19406            if (!isSystemApp(ps)) {
19407                // Do not uninstall the APK if an app should be cached
19408                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19409                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19410                    // Other user still have this package installed, so all
19411                    // we need to do is clear this user's data and save that
19412                    // it is uninstalled.
19413                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19414                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19415                        return false;
19416                    }
19417                    scheduleWritePackageRestrictionsLocked(user);
19418                    return true;
19419                } else {
19420                    // We need to set it back to 'installed' so the uninstall
19421                    // broadcasts will be sent correctly.
19422                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19423                    ps.setInstalled(true, user.getIdentifier());
19424                    mSettings.writeKernelMappingLPr(ps);
19425                }
19426            } else {
19427                // This is a system app, so we assume that the
19428                // other users still have this package installed, so all
19429                // we need to do is clear this user's data and save that
19430                // it is uninstalled.
19431                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19432                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19433                    return false;
19434                }
19435                scheduleWritePackageRestrictionsLocked(user);
19436                return true;
19437            }
19438        }
19439
19440        // If we are deleting a composite package for all users, keep track
19441        // of result for each child.
19442        if (ps.childPackageNames != null && outInfo != null) {
19443            synchronized (mPackages) {
19444                final int childCount = ps.childPackageNames.size();
19445                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19446                for (int i = 0; i < childCount; i++) {
19447                    String childPackageName = ps.childPackageNames.get(i);
19448                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19449                    childInfo.removedPackage = childPackageName;
19450                    childInfo.installerPackageName = ps.installerPackageName;
19451                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19452                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19453                    if (childPs != null) {
19454                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19455                    }
19456                }
19457            }
19458        }
19459
19460        boolean ret = false;
19461        if (isSystemApp(ps)) {
19462            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19463            // When an updated system application is deleted we delete the existing resources
19464            // as well and fall back to existing code in system partition
19465            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19466        } else {
19467            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19468            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19469                    outInfo, writeSettings, replacingPackage);
19470        }
19471
19472        // Take a note whether we deleted the package for all users
19473        if (outInfo != null) {
19474            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19475            if (outInfo.removedChildPackages != null) {
19476                synchronized (mPackages) {
19477                    final int childCount = outInfo.removedChildPackages.size();
19478                    for (int i = 0; i < childCount; i++) {
19479                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19480                        if (childInfo != null) {
19481                            childInfo.removedForAllUsers = mPackages.get(
19482                                    childInfo.removedPackage) == null;
19483                        }
19484                    }
19485                }
19486            }
19487            // If we uninstalled an update to a system app there may be some
19488            // child packages that appeared as they are declared in the system
19489            // app but were not declared in the update.
19490            if (isSystemApp(ps)) {
19491                synchronized (mPackages) {
19492                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19493                    final int childCount = (updatedPs.childPackageNames != null)
19494                            ? updatedPs.childPackageNames.size() : 0;
19495                    for (int i = 0; i < childCount; i++) {
19496                        String childPackageName = updatedPs.childPackageNames.get(i);
19497                        if (outInfo.removedChildPackages == null
19498                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19499                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19500                            if (childPs == null) {
19501                                continue;
19502                            }
19503                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19504                            installRes.name = childPackageName;
19505                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19506                            installRes.pkg = mPackages.get(childPackageName);
19507                            installRes.uid = childPs.pkg.applicationInfo.uid;
19508                            if (outInfo.appearedChildPackages == null) {
19509                                outInfo.appearedChildPackages = new ArrayMap<>();
19510                            }
19511                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19512                        }
19513                    }
19514                }
19515            }
19516        }
19517
19518        return ret;
19519    }
19520
19521    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19522        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19523                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19524        for (int nextUserId : userIds) {
19525            if (DEBUG_REMOVE) {
19526                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19527            }
19528            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19529                    false /*installed*/,
19530                    true /*stopped*/,
19531                    true /*notLaunched*/,
19532                    false /*hidden*/,
19533                    false /*suspended*/,
19534                    false /*instantApp*/,
19535                    null /*lastDisableAppCaller*/,
19536                    null /*enabledComponents*/,
19537                    null /*disabledComponents*/,
19538                    ps.readUserState(nextUserId).domainVerificationStatus,
19539                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19540        }
19541        mSettings.writeKernelMappingLPr(ps);
19542    }
19543
19544    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19545            PackageRemovedInfo outInfo) {
19546        final PackageParser.Package pkg;
19547        synchronized (mPackages) {
19548            pkg = mPackages.get(ps.name);
19549        }
19550
19551        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19552                : new int[] {userId};
19553        for (int nextUserId : userIds) {
19554            if (DEBUG_REMOVE) {
19555                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19556                        + nextUserId);
19557            }
19558
19559            destroyAppDataLIF(pkg, userId,
19560                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19561            destroyAppProfilesLIF(pkg, userId);
19562            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19563            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19564            schedulePackageCleaning(ps.name, nextUserId, false);
19565            synchronized (mPackages) {
19566                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19567                    scheduleWritePackageRestrictionsLocked(nextUserId);
19568                }
19569                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19570            }
19571        }
19572
19573        if (outInfo != null) {
19574            outInfo.removedPackage = ps.name;
19575            outInfo.installerPackageName = ps.installerPackageName;
19576            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19577            outInfo.removedAppId = ps.appId;
19578            outInfo.removedUsers = userIds;
19579            outInfo.broadcastUsers = userIds;
19580        }
19581
19582        return true;
19583    }
19584
19585    private final class ClearStorageConnection implements ServiceConnection {
19586        IMediaContainerService mContainerService;
19587
19588        @Override
19589        public void onServiceConnected(ComponentName name, IBinder service) {
19590            synchronized (this) {
19591                mContainerService = IMediaContainerService.Stub
19592                        .asInterface(Binder.allowBlocking(service));
19593                notifyAll();
19594            }
19595        }
19596
19597        @Override
19598        public void onServiceDisconnected(ComponentName name) {
19599        }
19600    }
19601
19602    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19603        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19604
19605        final boolean mounted;
19606        if (Environment.isExternalStorageEmulated()) {
19607            mounted = true;
19608        } else {
19609            final String status = Environment.getExternalStorageState();
19610
19611            mounted = status.equals(Environment.MEDIA_MOUNTED)
19612                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19613        }
19614
19615        if (!mounted) {
19616            return;
19617        }
19618
19619        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19620        int[] users;
19621        if (userId == UserHandle.USER_ALL) {
19622            users = sUserManager.getUserIds();
19623        } else {
19624            users = new int[] { userId };
19625        }
19626        final ClearStorageConnection conn = new ClearStorageConnection();
19627        if (mContext.bindServiceAsUser(
19628                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19629            try {
19630                for (int curUser : users) {
19631                    long timeout = SystemClock.uptimeMillis() + 5000;
19632                    synchronized (conn) {
19633                        long now;
19634                        while (conn.mContainerService == null &&
19635                                (now = SystemClock.uptimeMillis()) < timeout) {
19636                            try {
19637                                conn.wait(timeout - now);
19638                            } catch (InterruptedException e) {
19639                            }
19640                        }
19641                    }
19642                    if (conn.mContainerService == null) {
19643                        return;
19644                    }
19645
19646                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19647                    clearDirectory(conn.mContainerService,
19648                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19649                    if (allData) {
19650                        clearDirectory(conn.mContainerService,
19651                                userEnv.buildExternalStorageAppDataDirs(packageName));
19652                        clearDirectory(conn.mContainerService,
19653                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19654                    }
19655                }
19656            } finally {
19657                mContext.unbindService(conn);
19658            }
19659        }
19660    }
19661
19662    @Override
19663    public void clearApplicationProfileData(String packageName) {
19664        enforceSystemOrRoot("Only the system can clear all profile data");
19665
19666        final PackageParser.Package pkg;
19667        synchronized (mPackages) {
19668            pkg = mPackages.get(packageName);
19669        }
19670
19671        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19672            synchronized (mInstallLock) {
19673                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19674            }
19675        }
19676    }
19677
19678    @Override
19679    public void clearApplicationUserData(final String packageName,
19680            final IPackageDataObserver observer, final int userId) {
19681        mContext.enforceCallingOrSelfPermission(
19682                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19683
19684        final int callingUid = Binder.getCallingUid();
19685        enforceCrossUserPermission(callingUid, userId,
19686                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19687
19688        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19689        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19690            return;
19691        }
19692        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19693            throw new SecurityException("Cannot clear data for a protected package: "
19694                    + packageName);
19695        }
19696        // Queue up an async operation since the package deletion may take a little while.
19697        mHandler.post(new Runnable() {
19698            public void run() {
19699                mHandler.removeCallbacks(this);
19700                final boolean succeeded;
19701                try (PackageFreezer freezer = freezePackage(packageName,
19702                        "clearApplicationUserData")) {
19703                    synchronized (mInstallLock) {
19704                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19705                    }
19706                    clearExternalStorageDataSync(packageName, userId, true);
19707                    synchronized (mPackages) {
19708                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19709                                packageName, userId);
19710                    }
19711                }
19712                if (succeeded) {
19713                    // invoke DeviceStorageMonitor's update method to clear any notifications
19714                    DeviceStorageMonitorInternal dsm = LocalServices
19715                            .getService(DeviceStorageMonitorInternal.class);
19716                    if (dsm != null) {
19717                        dsm.checkMemory();
19718                    }
19719                }
19720                if(observer != null) {
19721                    try {
19722                        observer.onRemoveCompleted(packageName, succeeded);
19723                    } catch (RemoteException e) {
19724                        Log.i(TAG, "Observer no longer exists.");
19725                    }
19726                } //end if observer
19727            } //end run
19728        });
19729    }
19730
19731    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19732        if (packageName == null) {
19733            Slog.w(TAG, "Attempt to delete null packageName.");
19734            return false;
19735        }
19736
19737        // Try finding details about the requested package
19738        PackageParser.Package pkg;
19739        synchronized (mPackages) {
19740            pkg = mPackages.get(packageName);
19741            if (pkg == null) {
19742                final PackageSetting ps = mSettings.mPackages.get(packageName);
19743                if (ps != null) {
19744                    pkg = ps.pkg;
19745                }
19746            }
19747
19748            if (pkg == null) {
19749                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19750                return false;
19751            }
19752
19753            PackageSetting ps = (PackageSetting) pkg.mExtras;
19754            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19755        }
19756
19757        clearAppDataLIF(pkg, userId,
19758                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19759
19760        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19761        removeKeystoreDataIfNeeded(userId, appId);
19762
19763        UserManagerInternal umInternal = getUserManagerInternal();
19764        final int flags;
19765        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19766            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19767        } else if (umInternal.isUserRunning(userId)) {
19768            flags = StorageManager.FLAG_STORAGE_DE;
19769        } else {
19770            flags = 0;
19771        }
19772        prepareAppDataContentsLIF(pkg, userId, flags);
19773
19774        return true;
19775    }
19776
19777    /**
19778     * Reverts user permission state changes (permissions and flags) in
19779     * all packages for a given user.
19780     *
19781     * @param userId The device user for which to do a reset.
19782     */
19783    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19784        final int packageCount = mPackages.size();
19785        for (int i = 0; i < packageCount; i++) {
19786            PackageParser.Package pkg = mPackages.valueAt(i);
19787            PackageSetting ps = (PackageSetting) pkg.mExtras;
19788            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19789        }
19790    }
19791
19792    private void resetNetworkPolicies(int userId) {
19793        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19794    }
19795
19796    /**
19797     * Reverts user permission state changes (permissions and flags).
19798     *
19799     * @param ps The package for which to reset.
19800     * @param userId The device user for which to do a reset.
19801     */
19802    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19803            final PackageSetting ps, final int userId) {
19804        if (ps.pkg == null) {
19805            return;
19806        }
19807
19808        // These are flags that can change base on user actions.
19809        final int userSettableMask = FLAG_PERMISSION_USER_SET
19810                | FLAG_PERMISSION_USER_FIXED
19811                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19812                | FLAG_PERMISSION_REVIEW_REQUIRED;
19813
19814        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19815                | FLAG_PERMISSION_POLICY_FIXED;
19816
19817        boolean writeInstallPermissions = false;
19818        boolean writeRuntimePermissions = false;
19819
19820        final int permissionCount = ps.pkg.requestedPermissions.size();
19821        for (int i = 0; i < permissionCount; i++) {
19822            String permission = ps.pkg.requestedPermissions.get(i);
19823
19824            BasePermission bp = mSettings.mPermissions.get(permission);
19825            if (bp == null) {
19826                continue;
19827            }
19828
19829            // If shared user we just reset the state to which only this app contributed.
19830            if (ps.sharedUser != null) {
19831                boolean used = false;
19832                final int packageCount = ps.sharedUser.packages.size();
19833                for (int j = 0; j < packageCount; j++) {
19834                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19835                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19836                            && pkg.pkg.requestedPermissions.contains(permission)) {
19837                        used = true;
19838                        break;
19839                    }
19840                }
19841                if (used) {
19842                    continue;
19843                }
19844            }
19845
19846            PermissionsState permissionsState = ps.getPermissionsState();
19847
19848            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19849
19850            // Always clear the user settable flags.
19851            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19852                    bp.name) != null;
19853            // If permission review is enabled and this is a legacy app, mark the
19854            // permission as requiring a review as this is the initial state.
19855            int flags = 0;
19856            if (mPermissionReviewRequired
19857                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19858                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19859            }
19860            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19861                if (hasInstallState) {
19862                    writeInstallPermissions = true;
19863                } else {
19864                    writeRuntimePermissions = true;
19865                }
19866            }
19867
19868            // Below is only runtime permission handling.
19869            if (!bp.isRuntime()) {
19870                continue;
19871            }
19872
19873            // Never clobber system or policy.
19874            if ((oldFlags & policyOrSystemFlags) != 0) {
19875                continue;
19876            }
19877
19878            // If this permission was granted by default, make sure it is.
19879            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19880                if (permissionsState.grantRuntimePermission(bp, userId)
19881                        != PERMISSION_OPERATION_FAILURE) {
19882                    writeRuntimePermissions = true;
19883                }
19884            // If permission review is enabled the permissions for a legacy apps
19885            // are represented as constantly granted runtime ones, so don't revoke.
19886            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19887                // Otherwise, reset the permission.
19888                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19889                switch (revokeResult) {
19890                    case PERMISSION_OPERATION_SUCCESS:
19891                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19892                        writeRuntimePermissions = true;
19893                        final int appId = ps.appId;
19894                        mHandler.post(new Runnable() {
19895                            @Override
19896                            public void run() {
19897                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19898                            }
19899                        });
19900                    } break;
19901                }
19902            }
19903        }
19904
19905        // Synchronously write as we are taking permissions away.
19906        if (writeRuntimePermissions) {
19907            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19908        }
19909
19910        // Synchronously write as we are taking permissions away.
19911        if (writeInstallPermissions) {
19912            mSettings.writeLPr();
19913        }
19914    }
19915
19916    /**
19917     * Remove entries from the keystore daemon. Will only remove it if the
19918     * {@code appId} is valid.
19919     */
19920    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19921        if (appId < 0) {
19922            return;
19923        }
19924
19925        final KeyStore keyStore = KeyStore.getInstance();
19926        if (keyStore != null) {
19927            if (userId == UserHandle.USER_ALL) {
19928                for (final int individual : sUserManager.getUserIds()) {
19929                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19930                }
19931            } else {
19932                keyStore.clearUid(UserHandle.getUid(userId, appId));
19933            }
19934        } else {
19935            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19936        }
19937    }
19938
19939    @Override
19940    public void deleteApplicationCacheFiles(final String packageName,
19941            final IPackageDataObserver observer) {
19942        final int userId = UserHandle.getCallingUserId();
19943        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19944    }
19945
19946    @Override
19947    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19948            final IPackageDataObserver observer) {
19949        final int callingUid = Binder.getCallingUid();
19950        mContext.enforceCallingOrSelfPermission(
19951                android.Manifest.permission.DELETE_CACHE_FILES, null);
19952        enforceCrossUserPermission(callingUid, userId,
19953                /* requireFullPermission= */ true, /* checkShell= */ false,
19954                "delete application cache files");
19955        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19956                android.Manifest.permission.ACCESS_INSTANT_APPS);
19957
19958        final PackageParser.Package pkg;
19959        synchronized (mPackages) {
19960            pkg = mPackages.get(packageName);
19961        }
19962
19963        // Queue up an async operation since the package deletion may take a little while.
19964        mHandler.post(new Runnable() {
19965            public void run() {
19966                final PackageSetting ps = (PackageSetting) pkg.mExtras;
19967                boolean doClearData = true;
19968                if (ps != null) {
19969                    final boolean targetIsInstantApp =
19970                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19971                    doClearData = !targetIsInstantApp
19972                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19973                }
19974                if (doClearData) {
19975                    synchronized (mInstallLock) {
19976                        final int flags = StorageManager.FLAG_STORAGE_DE
19977                                | StorageManager.FLAG_STORAGE_CE;
19978                        // We're only clearing cache files, so we don't care if the
19979                        // app is unfrozen and still able to run
19980                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19981                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19982                    }
19983                    clearExternalStorageDataSync(packageName, userId, false);
19984                }
19985                if (observer != null) {
19986                    try {
19987                        observer.onRemoveCompleted(packageName, true);
19988                    } catch (RemoteException e) {
19989                        Log.i(TAG, "Observer no longer exists.");
19990                    }
19991                }
19992            }
19993        });
19994    }
19995
19996    @Override
19997    public void getPackageSizeInfo(final String packageName, int userHandle,
19998            final IPackageStatsObserver observer) {
19999        throw new UnsupportedOperationException(
20000                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20001    }
20002
20003    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20004        final PackageSetting ps;
20005        synchronized (mPackages) {
20006            ps = mSettings.mPackages.get(packageName);
20007            if (ps == null) {
20008                Slog.w(TAG, "Failed to find settings for " + packageName);
20009                return false;
20010            }
20011        }
20012
20013        final String[] packageNames = { packageName };
20014        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20015        final String[] codePaths = { ps.codePathString };
20016
20017        try {
20018            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20019                    ps.appId, ceDataInodes, codePaths, stats);
20020
20021            // For now, ignore code size of packages on system partition
20022            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20023                stats.codeSize = 0;
20024            }
20025
20026            // External clients expect these to be tracked separately
20027            stats.dataSize -= stats.cacheSize;
20028
20029        } catch (InstallerException e) {
20030            Slog.w(TAG, String.valueOf(e));
20031            return false;
20032        }
20033
20034        return true;
20035    }
20036
20037    private int getUidTargetSdkVersionLockedLPr(int uid) {
20038        Object obj = mSettings.getUserIdLPr(uid);
20039        if (obj instanceof SharedUserSetting) {
20040            final SharedUserSetting sus = (SharedUserSetting) obj;
20041            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20042            final Iterator<PackageSetting> it = sus.packages.iterator();
20043            while (it.hasNext()) {
20044                final PackageSetting ps = it.next();
20045                if (ps.pkg != null) {
20046                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20047                    if (v < vers) vers = v;
20048                }
20049            }
20050            return vers;
20051        } else if (obj instanceof PackageSetting) {
20052            final PackageSetting ps = (PackageSetting) obj;
20053            if (ps.pkg != null) {
20054                return ps.pkg.applicationInfo.targetSdkVersion;
20055            }
20056        }
20057        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20058    }
20059
20060    @Override
20061    public void addPreferredActivity(IntentFilter filter, int match,
20062            ComponentName[] set, ComponentName activity, int userId) {
20063        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20064                "Adding preferred");
20065    }
20066
20067    private void addPreferredActivityInternal(IntentFilter filter, int match,
20068            ComponentName[] set, ComponentName activity, boolean always, int userId,
20069            String opname) {
20070        // writer
20071        int callingUid = Binder.getCallingUid();
20072        enforceCrossUserPermission(callingUid, userId,
20073                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20074        if (filter.countActions() == 0) {
20075            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20076            return;
20077        }
20078        synchronized (mPackages) {
20079            if (mContext.checkCallingOrSelfPermission(
20080                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20081                    != PackageManager.PERMISSION_GRANTED) {
20082                if (getUidTargetSdkVersionLockedLPr(callingUid)
20083                        < Build.VERSION_CODES.FROYO) {
20084                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20085                            + callingUid);
20086                    return;
20087                }
20088                mContext.enforceCallingOrSelfPermission(
20089                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20090            }
20091
20092            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20093            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20094                    + userId + ":");
20095            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20096            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20097            scheduleWritePackageRestrictionsLocked(userId);
20098            postPreferredActivityChangedBroadcast(userId);
20099        }
20100    }
20101
20102    private void postPreferredActivityChangedBroadcast(int userId) {
20103        mHandler.post(() -> {
20104            final IActivityManager am = ActivityManager.getService();
20105            if (am == null) {
20106                return;
20107            }
20108
20109            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20110            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20111            try {
20112                am.broadcastIntent(null, intent, null, null,
20113                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20114                        null, false, false, userId);
20115            } catch (RemoteException e) {
20116            }
20117        });
20118    }
20119
20120    @Override
20121    public void replacePreferredActivity(IntentFilter filter, int match,
20122            ComponentName[] set, ComponentName activity, int userId) {
20123        if (filter.countActions() != 1) {
20124            throw new IllegalArgumentException(
20125                    "replacePreferredActivity expects filter to have only 1 action.");
20126        }
20127        if (filter.countDataAuthorities() != 0
20128                || filter.countDataPaths() != 0
20129                || filter.countDataSchemes() > 1
20130                || filter.countDataTypes() != 0) {
20131            throw new IllegalArgumentException(
20132                    "replacePreferredActivity expects filter to have no data authorities, " +
20133                    "paths, or types; and at most one scheme.");
20134        }
20135
20136        final int callingUid = Binder.getCallingUid();
20137        enforceCrossUserPermission(callingUid, userId,
20138                true /* requireFullPermission */, false /* checkShell */,
20139                "replace preferred activity");
20140        synchronized (mPackages) {
20141            if (mContext.checkCallingOrSelfPermission(
20142                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20143                    != PackageManager.PERMISSION_GRANTED) {
20144                if (getUidTargetSdkVersionLockedLPr(callingUid)
20145                        < Build.VERSION_CODES.FROYO) {
20146                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20147                            + Binder.getCallingUid());
20148                    return;
20149                }
20150                mContext.enforceCallingOrSelfPermission(
20151                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20152            }
20153
20154            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20155            if (pir != null) {
20156                // Get all of the existing entries that exactly match this filter.
20157                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20158                if (existing != null && existing.size() == 1) {
20159                    PreferredActivity cur = existing.get(0);
20160                    if (DEBUG_PREFERRED) {
20161                        Slog.i(TAG, "Checking replace of preferred:");
20162                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20163                        if (!cur.mPref.mAlways) {
20164                            Slog.i(TAG, "  -- CUR; not mAlways!");
20165                        } else {
20166                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20167                            Slog.i(TAG, "  -- CUR: mSet="
20168                                    + Arrays.toString(cur.mPref.mSetComponents));
20169                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20170                            Slog.i(TAG, "  -- NEW: mMatch="
20171                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20172                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20173                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20174                        }
20175                    }
20176                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20177                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20178                            && cur.mPref.sameSet(set)) {
20179                        // Setting the preferred activity to what it happens to be already
20180                        if (DEBUG_PREFERRED) {
20181                            Slog.i(TAG, "Replacing with same preferred activity "
20182                                    + cur.mPref.mShortComponent + " for user "
20183                                    + userId + ":");
20184                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20185                        }
20186                        return;
20187                    }
20188                }
20189
20190                if (existing != null) {
20191                    if (DEBUG_PREFERRED) {
20192                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20193                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20194                    }
20195                    for (int i = 0; i < existing.size(); i++) {
20196                        PreferredActivity pa = existing.get(i);
20197                        if (DEBUG_PREFERRED) {
20198                            Slog.i(TAG, "Removing existing preferred activity "
20199                                    + pa.mPref.mComponent + ":");
20200                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20201                        }
20202                        pir.removeFilter(pa);
20203                    }
20204                }
20205            }
20206            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20207                    "Replacing preferred");
20208        }
20209    }
20210
20211    @Override
20212    public void clearPackagePreferredActivities(String packageName) {
20213        final int callingUid = Binder.getCallingUid();
20214        if (getInstantAppPackageName(callingUid) != null) {
20215            return;
20216        }
20217        // writer
20218        synchronized (mPackages) {
20219            PackageParser.Package pkg = mPackages.get(packageName);
20220            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20221                if (mContext.checkCallingOrSelfPermission(
20222                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20223                        != PackageManager.PERMISSION_GRANTED) {
20224                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20225                            < Build.VERSION_CODES.FROYO) {
20226                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20227                                + callingUid);
20228                        return;
20229                    }
20230                    mContext.enforceCallingOrSelfPermission(
20231                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20232                }
20233            }
20234            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20235            if (ps != null
20236                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20237                return;
20238            }
20239            int user = UserHandle.getCallingUserId();
20240            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20241                scheduleWritePackageRestrictionsLocked(user);
20242            }
20243        }
20244    }
20245
20246    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20247    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20248        ArrayList<PreferredActivity> removed = null;
20249        boolean changed = false;
20250        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20251            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20252            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20253            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20254                continue;
20255            }
20256            Iterator<PreferredActivity> it = pir.filterIterator();
20257            while (it.hasNext()) {
20258                PreferredActivity pa = it.next();
20259                // Mark entry for removal only if it matches the package name
20260                // and the entry is of type "always".
20261                if (packageName == null ||
20262                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20263                                && pa.mPref.mAlways)) {
20264                    if (removed == null) {
20265                        removed = new ArrayList<PreferredActivity>();
20266                    }
20267                    removed.add(pa);
20268                }
20269            }
20270            if (removed != null) {
20271                for (int j=0; j<removed.size(); j++) {
20272                    PreferredActivity pa = removed.get(j);
20273                    pir.removeFilter(pa);
20274                }
20275                changed = true;
20276            }
20277        }
20278        if (changed) {
20279            postPreferredActivityChangedBroadcast(userId);
20280        }
20281        return changed;
20282    }
20283
20284    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20285    private void clearIntentFilterVerificationsLPw(int userId) {
20286        final int packageCount = mPackages.size();
20287        for (int i = 0; i < packageCount; i++) {
20288            PackageParser.Package pkg = mPackages.valueAt(i);
20289            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20290        }
20291    }
20292
20293    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20294    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20295        if (userId == UserHandle.USER_ALL) {
20296            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20297                    sUserManager.getUserIds())) {
20298                for (int oneUserId : sUserManager.getUserIds()) {
20299                    scheduleWritePackageRestrictionsLocked(oneUserId);
20300                }
20301            }
20302        } else {
20303            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20304                scheduleWritePackageRestrictionsLocked(userId);
20305            }
20306        }
20307    }
20308
20309    /** Clears state for all users, and touches intent filter verification policy */
20310    void clearDefaultBrowserIfNeeded(String packageName) {
20311        for (int oneUserId : sUserManager.getUserIds()) {
20312            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20313        }
20314    }
20315
20316    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20317        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20318        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20319            if (packageName.equals(defaultBrowserPackageName)) {
20320                setDefaultBrowserPackageName(null, userId);
20321            }
20322        }
20323    }
20324
20325    @Override
20326    public void resetApplicationPreferences(int userId) {
20327        mContext.enforceCallingOrSelfPermission(
20328                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20329        final long identity = Binder.clearCallingIdentity();
20330        // writer
20331        try {
20332            synchronized (mPackages) {
20333                clearPackagePreferredActivitiesLPw(null, userId);
20334                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20335                // TODO: We have to reset the default SMS and Phone. This requires
20336                // significant refactoring to keep all default apps in the package
20337                // manager (cleaner but more work) or have the services provide
20338                // callbacks to the package manager to request a default app reset.
20339                applyFactoryDefaultBrowserLPw(userId);
20340                clearIntentFilterVerificationsLPw(userId);
20341                primeDomainVerificationsLPw(userId);
20342                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20343                scheduleWritePackageRestrictionsLocked(userId);
20344            }
20345            resetNetworkPolicies(userId);
20346        } finally {
20347            Binder.restoreCallingIdentity(identity);
20348        }
20349    }
20350
20351    @Override
20352    public int getPreferredActivities(List<IntentFilter> outFilters,
20353            List<ComponentName> outActivities, String packageName) {
20354        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20355            return 0;
20356        }
20357        int num = 0;
20358        final int userId = UserHandle.getCallingUserId();
20359        // reader
20360        synchronized (mPackages) {
20361            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20362            if (pir != null) {
20363                final Iterator<PreferredActivity> it = pir.filterIterator();
20364                while (it.hasNext()) {
20365                    final PreferredActivity pa = it.next();
20366                    if (packageName == null
20367                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20368                                    && pa.mPref.mAlways)) {
20369                        if (outFilters != null) {
20370                            outFilters.add(new IntentFilter(pa));
20371                        }
20372                        if (outActivities != null) {
20373                            outActivities.add(pa.mPref.mComponent);
20374                        }
20375                    }
20376                }
20377            }
20378        }
20379
20380        return num;
20381    }
20382
20383    @Override
20384    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20385            int userId) {
20386        int callingUid = Binder.getCallingUid();
20387        if (callingUid != Process.SYSTEM_UID) {
20388            throw new SecurityException(
20389                    "addPersistentPreferredActivity can only be run by the system");
20390        }
20391        if (filter.countActions() == 0) {
20392            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20393            return;
20394        }
20395        synchronized (mPackages) {
20396            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20397                    ":");
20398            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20399            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20400                    new PersistentPreferredActivity(filter, activity));
20401            scheduleWritePackageRestrictionsLocked(userId);
20402            postPreferredActivityChangedBroadcast(userId);
20403        }
20404    }
20405
20406    @Override
20407    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20408        int callingUid = Binder.getCallingUid();
20409        if (callingUid != Process.SYSTEM_UID) {
20410            throw new SecurityException(
20411                    "clearPackagePersistentPreferredActivities can only be run by the system");
20412        }
20413        ArrayList<PersistentPreferredActivity> removed = null;
20414        boolean changed = false;
20415        synchronized (mPackages) {
20416            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20417                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20418                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20419                        .valueAt(i);
20420                if (userId != thisUserId) {
20421                    continue;
20422                }
20423                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20424                while (it.hasNext()) {
20425                    PersistentPreferredActivity ppa = it.next();
20426                    // Mark entry for removal only if it matches the package name.
20427                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20428                        if (removed == null) {
20429                            removed = new ArrayList<PersistentPreferredActivity>();
20430                        }
20431                        removed.add(ppa);
20432                    }
20433                }
20434                if (removed != null) {
20435                    for (int j=0; j<removed.size(); j++) {
20436                        PersistentPreferredActivity ppa = removed.get(j);
20437                        ppir.removeFilter(ppa);
20438                    }
20439                    changed = true;
20440                }
20441            }
20442
20443            if (changed) {
20444                scheduleWritePackageRestrictionsLocked(userId);
20445                postPreferredActivityChangedBroadcast(userId);
20446            }
20447        }
20448    }
20449
20450    /**
20451     * Common machinery for picking apart a restored XML blob and passing
20452     * it to a caller-supplied functor to be applied to the running system.
20453     */
20454    private void restoreFromXml(XmlPullParser parser, int userId,
20455            String expectedStartTag, BlobXmlRestorer functor)
20456            throws IOException, XmlPullParserException {
20457        int type;
20458        while ((type = parser.next()) != XmlPullParser.START_TAG
20459                && type != XmlPullParser.END_DOCUMENT) {
20460        }
20461        if (type != XmlPullParser.START_TAG) {
20462            // oops didn't find a start tag?!
20463            if (DEBUG_BACKUP) {
20464                Slog.e(TAG, "Didn't find start tag during restore");
20465            }
20466            return;
20467        }
20468Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20469        // this is supposed to be TAG_PREFERRED_BACKUP
20470        if (!expectedStartTag.equals(parser.getName())) {
20471            if (DEBUG_BACKUP) {
20472                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20473            }
20474            return;
20475        }
20476
20477        // skip interfering stuff, then we're aligned with the backing implementation
20478        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20479Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20480        functor.apply(parser, userId);
20481    }
20482
20483    private interface BlobXmlRestorer {
20484        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20485    }
20486
20487    /**
20488     * Non-Binder method, support for the backup/restore mechanism: write the
20489     * full set of preferred activities in its canonical XML format.  Returns the
20490     * XML output as a byte array, or null if there is none.
20491     */
20492    @Override
20493    public byte[] getPreferredActivityBackup(int userId) {
20494        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20495            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20496        }
20497
20498        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20499        try {
20500            final XmlSerializer serializer = new FastXmlSerializer();
20501            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20502            serializer.startDocument(null, true);
20503            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20504
20505            synchronized (mPackages) {
20506                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20507            }
20508
20509            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20510            serializer.endDocument();
20511            serializer.flush();
20512        } catch (Exception e) {
20513            if (DEBUG_BACKUP) {
20514                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20515            }
20516            return null;
20517        }
20518
20519        return dataStream.toByteArray();
20520    }
20521
20522    @Override
20523    public void restorePreferredActivities(byte[] backup, int userId) {
20524        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20525            throw new SecurityException("Only the system may call restorePreferredActivities()");
20526        }
20527
20528        try {
20529            final XmlPullParser parser = Xml.newPullParser();
20530            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20531            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20532                    new BlobXmlRestorer() {
20533                        @Override
20534                        public void apply(XmlPullParser parser, int userId)
20535                                throws XmlPullParserException, IOException {
20536                            synchronized (mPackages) {
20537                                mSettings.readPreferredActivitiesLPw(parser, userId);
20538                            }
20539                        }
20540                    } );
20541        } catch (Exception e) {
20542            if (DEBUG_BACKUP) {
20543                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20544            }
20545        }
20546    }
20547
20548    /**
20549     * Non-Binder method, support for the backup/restore mechanism: write the
20550     * default browser (etc) settings in its canonical XML format.  Returns the default
20551     * browser XML representation as a byte array, or null if there is none.
20552     */
20553    @Override
20554    public byte[] getDefaultAppsBackup(int userId) {
20555        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20556            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20557        }
20558
20559        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20560        try {
20561            final XmlSerializer serializer = new FastXmlSerializer();
20562            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20563            serializer.startDocument(null, true);
20564            serializer.startTag(null, TAG_DEFAULT_APPS);
20565
20566            synchronized (mPackages) {
20567                mSettings.writeDefaultAppsLPr(serializer, userId);
20568            }
20569
20570            serializer.endTag(null, TAG_DEFAULT_APPS);
20571            serializer.endDocument();
20572            serializer.flush();
20573        } catch (Exception e) {
20574            if (DEBUG_BACKUP) {
20575                Slog.e(TAG, "Unable to write default apps for backup", e);
20576            }
20577            return null;
20578        }
20579
20580        return dataStream.toByteArray();
20581    }
20582
20583    @Override
20584    public void restoreDefaultApps(byte[] backup, int userId) {
20585        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20586            throw new SecurityException("Only the system may call restoreDefaultApps()");
20587        }
20588
20589        try {
20590            final XmlPullParser parser = Xml.newPullParser();
20591            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20592            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20593                    new BlobXmlRestorer() {
20594                        @Override
20595                        public void apply(XmlPullParser parser, int userId)
20596                                throws XmlPullParserException, IOException {
20597                            synchronized (mPackages) {
20598                                mSettings.readDefaultAppsLPw(parser, userId);
20599                            }
20600                        }
20601                    } );
20602        } catch (Exception e) {
20603            if (DEBUG_BACKUP) {
20604                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20605            }
20606        }
20607    }
20608
20609    @Override
20610    public byte[] getIntentFilterVerificationBackup(int userId) {
20611        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20612            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20613        }
20614
20615        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20616        try {
20617            final XmlSerializer serializer = new FastXmlSerializer();
20618            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20619            serializer.startDocument(null, true);
20620            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20621
20622            synchronized (mPackages) {
20623                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20624            }
20625
20626            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20627            serializer.endDocument();
20628            serializer.flush();
20629        } catch (Exception e) {
20630            if (DEBUG_BACKUP) {
20631                Slog.e(TAG, "Unable to write default apps for backup", e);
20632            }
20633            return null;
20634        }
20635
20636        return dataStream.toByteArray();
20637    }
20638
20639    @Override
20640    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20641        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20642            throw new SecurityException("Only the system may call restorePreferredActivities()");
20643        }
20644
20645        try {
20646            final XmlPullParser parser = Xml.newPullParser();
20647            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20648            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20649                    new BlobXmlRestorer() {
20650                        @Override
20651                        public void apply(XmlPullParser parser, int userId)
20652                                throws XmlPullParserException, IOException {
20653                            synchronized (mPackages) {
20654                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20655                                mSettings.writeLPr();
20656                            }
20657                        }
20658                    } );
20659        } catch (Exception e) {
20660            if (DEBUG_BACKUP) {
20661                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20662            }
20663        }
20664    }
20665
20666    @Override
20667    public byte[] getPermissionGrantBackup(int userId) {
20668        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20669            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20670        }
20671
20672        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20673        try {
20674            final XmlSerializer serializer = new FastXmlSerializer();
20675            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20676            serializer.startDocument(null, true);
20677            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20678
20679            synchronized (mPackages) {
20680                serializeRuntimePermissionGrantsLPr(serializer, userId);
20681            }
20682
20683            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20684            serializer.endDocument();
20685            serializer.flush();
20686        } catch (Exception e) {
20687            if (DEBUG_BACKUP) {
20688                Slog.e(TAG, "Unable to write default apps for backup", e);
20689            }
20690            return null;
20691        }
20692
20693        return dataStream.toByteArray();
20694    }
20695
20696    @Override
20697    public void restorePermissionGrants(byte[] backup, int userId) {
20698        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20699            throw new SecurityException("Only the system may call restorePermissionGrants()");
20700        }
20701
20702        try {
20703            final XmlPullParser parser = Xml.newPullParser();
20704            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20705            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20706                    new BlobXmlRestorer() {
20707                        @Override
20708                        public void apply(XmlPullParser parser, int userId)
20709                                throws XmlPullParserException, IOException {
20710                            synchronized (mPackages) {
20711                                processRestoredPermissionGrantsLPr(parser, userId);
20712                            }
20713                        }
20714                    } );
20715        } catch (Exception e) {
20716            if (DEBUG_BACKUP) {
20717                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20718            }
20719        }
20720    }
20721
20722    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20723            throws IOException {
20724        serializer.startTag(null, TAG_ALL_GRANTS);
20725
20726        final int N = mSettings.mPackages.size();
20727        for (int i = 0; i < N; i++) {
20728            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20729            boolean pkgGrantsKnown = false;
20730
20731            PermissionsState packagePerms = ps.getPermissionsState();
20732
20733            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20734                final int grantFlags = state.getFlags();
20735                // only look at grants that are not system/policy fixed
20736                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20737                    final boolean isGranted = state.isGranted();
20738                    // And only back up the user-twiddled state bits
20739                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20740                        final String packageName = mSettings.mPackages.keyAt(i);
20741                        if (!pkgGrantsKnown) {
20742                            serializer.startTag(null, TAG_GRANT);
20743                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20744                            pkgGrantsKnown = true;
20745                        }
20746
20747                        final boolean userSet =
20748                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20749                        final boolean userFixed =
20750                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20751                        final boolean revoke =
20752                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20753
20754                        serializer.startTag(null, TAG_PERMISSION);
20755                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20756                        if (isGranted) {
20757                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20758                        }
20759                        if (userSet) {
20760                            serializer.attribute(null, ATTR_USER_SET, "true");
20761                        }
20762                        if (userFixed) {
20763                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20764                        }
20765                        if (revoke) {
20766                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20767                        }
20768                        serializer.endTag(null, TAG_PERMISSION);
20769                    }
20770                }
20771            }
20772
20773            if (pkgGrantsKnown) {
20774                serializer.endTag(null, TAG_GRANT);
20775            }
20776        }
20777
20778        serializer.endTag(null, TAG_ALL_GRANTS);
20779    }
20780
20781    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20782            throws XmlPullParserException, IOException {
20783        String pkgName = null;
20784        int outerDepth = parser.getDepth();
20785        int type;
20786        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20787                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20788            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20789                continue;
20790            }
20791
20792            final String tagName = parser.getName();
20793            if (tagName.equals(TAG_GRANT)) {
20794                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20795                if (DEBUG_BACKUP) {
20796                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20797                }
20798            } else if (tagName.equals(TAG_PERMISSION)) {
20799
20800                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20801                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20802
20803                int newFlagSet = 0;
20804                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20805                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20806                }
20807                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20808                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20809                }
20810                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20811                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20812                }
20813                if (DEBUG_BACKUP) {
20814                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20815                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20816                }
20817                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20818                if (ps != null) {
20819                    // Already installed so we apply the grant immediately
20820                    if (DEBUG_BACKUP) {
20821                        Slog.v(TAG, "        + already installed; applying");
20822                    }
20823                    PermissionsState perms = ps.getPermissionsState();
20824                    BasePermission bp = mSettings.mPermissions.get(permName);
20825                    if (bp != null) {
20826                        if (isGranted) {
20827                            perms.grantRuntimePermission(bp, userId);
20828                        }
20829                        if (newFlagSet != 0) {
20830                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20831                        }
20832                    }
20833                } else {
20834                    // Need to wait for post-restore install to apply the grant
20835                    if (DEBUG_BACKUP) {
20836                        Slog.v(TAG, "        - not yet installed; saving for later");
20837                    }
20838                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20839                            isGranted, newFlagSet, userId);
20840                }
20841            } else {
20842                PackageManagerService.reportSettingsProblem(Log.WARN,
20843                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20844                XmlUtils.skipCurrentTag(parser);
20845            }
20846        }
20847
20848        scheduleWriteSettingsLocked();
20849        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20850    }
20851
20852    @Override
20853    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20854            int sourceUserId, int targetUserId, int flags) {
20855        mContext.enforceCallingOrSelfPermission(
20856                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20857        int callingUid = Binder.getCallingUid();
20858        enforceOwnerRights(ownerPackage, callingUid);
20859        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20860        if (intentFilter.countActions() == 0) {
20861            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20862            return;
20863        }
20864        synchronized (mPackages) {
20865            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20866                    ownerPackage, targetUserId, flags);
20867            CrossProfileIntentResolver resolver =
20868                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20869            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20870            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20871            if (existing != null) {
20872                int size = existing.size();
20873                for (int i = 0; i < size; i++) {
20874                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20875                        return;
20876                    }
20877                }
20878            }
20879            resolver.addFilter(newFilter);
20880            scheduleWritePackageRestrictionsLocked(sourceUserId);
20881        }
20882    }
20883
20884    @Override
20885    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20886        mContext.enforceCallingOrSelfPermission(
20887                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20888        final int callingUid = Binder.getCallingUid();
20889        enforceOwnerRights(ownerPackage, callingUid);
20890        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20891        synchronized (mPackages) {
20892            CrossProfileIntentResolver resolver =
20893                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20894            ArraySet<CrossProfileIntentFilter> set =
20895                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20896            for (CrossProfileIntentFilter filter : set) {
20897                if (filter.getOwnerPackage().equals(ownerPackage)) {
20898                    resolver.removeFilter(filter);
20899                }
20900            }
20901            scheduleWritePackageRestrictionsLocked(sourceUserId);
20902        }
20903    }
20904
20905    // Enforcing that callingUid is owning pkg on userId
20906    private void enforceOwnerRights(String pkg, int callingUid) {
20907        // The system owns everything.
20908        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20909            return;
20910        }
20911        final int callingUserId = UserHandle.getUserId(callingUid);
20912        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20913        if (pi == null) {
20914            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20915                    + callingUserId);
20916        }
20917        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20918            throw new SecurityException("Calling uid " + callingUid
20919                    + " does not own package " + pkg);
20920        }
20921    }
20922
20923    @Override
20924    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20925        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20926            return null;
20927        }
20928        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20929    }
20930
20931    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20932        UserManagerService ums = UserManagerService.getInstance();
20933        if (ums != null) {
20934            final UserInfo parent = ums.getProfileParent(userId);
20935            final int launcherUid = (parent != null) ? parent.id : userId;
20936            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20937            if (launcherComponent != null) {
20938                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20939                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20940                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20941                        .setPackage(launcherComponent.getPackageName());
20942                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20943            }
20944        }
20945    }
20946
20947    /**
20948     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20949     * then reports the most likely home activity or null if there are more than one.
20950     */
20951    private ComponentName getDefaultHomeActivity(int userId) {
20952        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20953        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20954        if (cn != null) {
20955            return cn;
20956        }
20957
20958        // Find the launcher with the highest priority and return that component if there are no
20959        // other home activity with the same priority.
20960        int lastPriority = Integer.MIN_VALUE;
20961        ComponentName lastComponent = null;
20962        final int size = allHomeCandidates.size();
20963        for (int i = 0; i < size; i++) {
20964            final ResolveInfo ri = allHomeCandidates.get(i);
20965            if (ri.priority > lastPriority) {
20966                lastComponent = ri.activityInfo.getComponentName();
20967                lastPriority = ri.priority;
20968            } else if (ri.priority == lastPriority) {
20969                // Two components found with same priority.
20970                lastComponent = null;
20971            }
20972        }
20973        return lastComponent;
20974    }
20975
20976    private Intent getHomeIntent() {
20977        Intent intent = new Intent(Intent.ACTION_MAIN);
20978        intent.addCategory(Intent.CATEGORY_HOME);
20979        intent.addCategory(Intent.CATEGORY_DEFAULT);
20980        return intent;
20981    }
20982
20983    private IntentFilter getHomeFilter() {
20984        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20985        filter.addCategory(Intent.CATEGORY_HOME);
20986        filter.addCategory(Intent.CATEGORY_DEFAULT);
20987        return filter;
20988    }
20989
20990    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20991            int userId) {
20992        Intent intent  = getHomeIntent();
20993        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20994                PackageManager.GET_META_DATA, userId);
20995        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20996                true, false, false, userId);
20997
20998        allHomeCandidates.clear();
20999        if (list != null) {
21000            for (ResolveInfo ri : list) {
21001                allHomeCandidates.add(ri);
21002            }
21003        }
21004        return (preferred == null || preferred.activityInfo == null)
21005                ? null
21006                : new ComponentName(preferred.activityInfo.packageName,
21007                        preferred.activityInfo.name);
21008    }
21009
21010    @Override
21011    public void setHomeActivity(ComponentName comp, int userId) {
21012        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21013            return;
21014        }
21015        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21016        getHomeActivitiesAsUser(homeActivities, userId);
21017
21018        boolean found = false;
21019
21020        final int size = homeActivities.size();
21021        final ComponentName[] set = new ComponentName[size];
21022        for (int i = 0; i < size; i++) {
21023            final ResolveInfo candidate = homeActivities.get(i);
21024            final ActivityInfo info = candidate.activityInfo;
21025            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21026            set[i] = activityName;
21027            if (!found && activityName.equals(comp)) {
21028                found = true;
21029            }
21030        }
21031        if (!found) {
21032            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21033                    + userId);
21034        }
21035        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21036                set, comp, userId);
21037    }
21038
21039    private @Nullable String getSetupWizardPackageName() {
21040        final Intent intent = new Intent(Intent.ACTION_MAIN);
21041        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21042
21043        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21044                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21045                        | MATCH_DISABLED_COMPONENTS,
21046                UserHandle.myUserId());
21047        if (matches.size() == 1) {
21048            return matches.get(0).getComponentInfo().packageName;
21049        } else {
21050            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21051                    + ": matches=" + matches);
21052            return null;
21053        }
21054    }
21055
21056    private @Nullable String getStorageManagerPackageName() {
21057        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21058
21059        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21060                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21061                        | MATCH_DISABLED_COMPONENTS,
21062                UserHandle.myUserId());
21063        if (matches.size() == 1) {
21064            return matches.get(0).getComponentInfo().packageName;
21065        } else {
21066            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21067                    + matches.size() + ": matches=" + matches);
21068            return null;
21069        }
21070    }
21071
21072    @Override
21073    public void setApplicationEnabledSetting(String appPackageName,
21074            int newState, int flags, int userId, String callingPackage) {
21075        if (!sUserManager.exists(userId)) return;
21076        if (callingPackage == null) {
21077            callingPackage = Integer.toString(Binder.getCallingUid());
21078        }
21079        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21080    }
21081
21082    @Override
21083    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21084        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21085        synchronized (mPackages) {
21086            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21087            if (pkgSetting != null) {
21088                pkgSetting.setUpdateAvailable(updateAvailable);
21089            }
21090        }
21091    }
21092
21093    @Override
21094    public void setComponentEnabledSetting(ComponentName componentName,
21095            int newState, int flags, int userId) {
21096        if (!sUserManager.exists(userId)) return;
21097        setEnabledSetting(componentName.getPackageName(),
21098                componentName.getClassName(), newState, flags, userId, null);
21099    }
21100
21101    private void setEnabledSetting(final String packageName, String className, int newState,
21102            final int flags, int userId, String callingPackage) {
21103        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21104              || newState == COMPONENT_ENABLED_STATE_ENABLED
21105              || newState == COMPONENT_ENABLED_STATE_DISABLED
21106              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21107              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21108            throw new IllegalArgumentException("Invalid new component state: "
21109                    + newState);
21110        }
21111        PackageSetting pkgSetting;
21112        final int callingUid = Binder.getCallingUid();
21113        final int permission;
21114        if (callingUid == Process.SYSTEM_UID) {
21115            permission = PackageManager.PERMISSION_GRANTED;
21116        } else {
21117            permission = mContext.checkCallingOrSelfPermission(
21118                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21119        }
21120        enforceCrossUserPermission(callingUid, userId,
21121                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21122        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21123        boolean sendNow = false;
21124        boolean isApp = (className == null);
21125        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21126        String componentName = isApp ? packageName : className;
21127        int packageUid = -1;
21128        ArrayList<String> components;
21129
21130        // reader
21131        synchronized (mPackages) {
21132            pkgSetting = mSettings.mPackages.get(packageName);
21133            if (pkgSetting == null) {
21134                if (!isCallerInstantApp) {
21135                    if (className == null) {
21136                        throw new IllegalArgumentException("Unknown package: " + packageName);
21137                    }
21138                    throw new IllegalArgumentException(
21139                            "Unknown component: " + packageName + "/" + className);
21140                } else {
21141                    // throw SecurityException to prevent leaking package information
21142                    throw new SecurityException(
21143                            "Attempt to change component state; "
21144                            + "pid=" + Binder.getCallingPid()
21145                            + ", uid=" + callingUid
21146                            + (className == null
21147                                    ? ", package=" + packageName
21148                                    : ", component=" + packageName + "/" + className));
21149                }
21150            }
21151        }
21152
21153        // Limit who can change which apps
21154        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21155            // Don't allow apps that don't have permission to modify other apps
21156            if (!allowedByPermission
21157                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21158                throw new SecurityException(
21159                        "Attempt to change component state; "
21160                        + "pid=" + Binder.getCallingPid()
21161                        + ", uid=" + callingUid
21162                        + (className == null
21163                                ? ", package=" + packageName
21164                                : ", component=" + packageName + "/" + className));
21165            }
21166            // Don't allow changing protected packages.
21167            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21168                throw new SecurityException("Cannot disable a protected package: " + packageName);
21169            }
21170        }
21171
21172        synchronized (mPackages) {
21173            if (callingUid == Process.SHELL_UID
21174                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21175                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21176                // unless it is a test package.
21177                int oldState = pkgSetting.getEnabled(userId);
21178                if (className == null
21179                    &&
21180                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21181                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21182                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21183                    &&
21184                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21185                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21186                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21187                    // ok
21188                } else {
21189                    throw new SecurityException(
21190                            "Shell cannot change component state for " + packageName + "/"
21191                            + className + " to " + newState);
21192                }
21193            }
21194            if (className == null) {
21195                // We're dealing with an application/package level state change
21196                if (pkgSetting.getEnabled(userId) == newState) {
21197                    // Nothing to do
21198                    return;
21199                }
21200                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21201                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21202                    // Don't care about who enables an app.
21203                    callingPackage = null;
21204                }
21205                pkgSetting.setEnabled(newState, userId, callingPackage);
21206                // pkgSetting.pkg.mSetEnabled = newState;
21207            } else {
21208                // We're dealing with a component level state change
21209                // First, verify that this is a valid class name.
21210                PackageParser.Package pkg = pkgSetting.pkg;
21211                if (pkg == null || !pkg.hasComponentClassName(className)) {
21212                    if (pkg != null &&
21213                            pkg.applicationInfo.targetSdkVersion >=
21214                                    Build.VERSION_CODES.JELLY_BEAN) {
21215                        throw new IllegalArgumentException("Component class " + className
21216                                + " does not exist in " + packageName);
21217                    } else {
21218                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21219                                + className + " does not exist in " + packageName);
21220                    }
21221                }
21222                switch (newState) {
21223                case COMPONENT_ENABLED_STATE_ENABLED:
21224                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21225                        return;
21226                    }
21227                    break;
21228                case COMPONENT_ENABLED_STATE_DISABLED:
21229                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21230                        return;
21231                    }
21232                    break;
21233                case COMPONENT_ENABLED_STATE_DEFAULT:
21234                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21235                        return;
21236                    }
21237                    break;
21238                default:
21239                    Slog.e(TAG, "Invalid new component state: " + newState);
21240                    return;
21241                }
21242            }
21243            scheduleWritePackageRestrictionsLocked(userId);
21244            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21245            final long callingId = Binder.clearCallingIdentity();
21246            try {
21247                updateInstantAppInstallerLocked(packageName);
21248            } finally {
21249                Binder.restoreCallingIdentity(callingId);
21250            }
21251            components = mPendingBroadcasts.get(userId, packageName);
21252            final boolean newPackage = components == null;
21253            if (newPackage) {
21254                components = new ArrayList<String>();
21255            }
21256            if (!components.contains(componentName)) {
21257                components.add(componentName);
21258            }
21259            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21260                sendNow = true;
21261                // Purge entry from pending broadcast list if another one exists already
21262                // since we are sending one right away.
21263                mPendingBroadcasts.remove(userId, packageName);
21264            } else {
21265                if (newPackage) {
21266                    mPendingBroadcasts.put(userId, packageName, components);
21267                }
21268                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21269                    // Schedule a message
21270                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21271                }
21272            }
21273        }
21274
21275        long callingId = Binder.clearCallingIdentity();
21276        try {
21277            if (sendNow) {
21278                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21279                sendPackageChangedBroadcast(packageName,
21280                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21281            }
21282        } finally {
21283            Binder.restoreCallingIdentity(callingId);
21284        }
21285    }
21286
21287    @Override
21288    public void flushPackageRestrictionsAsUser(int userId) {
21289        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21290            return;
21291        }
21292        if (!sUserManager.exists(userId)) {
21293            return;
21294        }
21295        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21296                false /* checkShell */, "flushPackageRestrictions");
21297        synchronized (mPackages) {
21298            mSettings.writePackageRestrictionsLPr(userId);
21299            mDirtyUsers.remove(userId);
21300            if (mDirtyUsers.isEmpty()) {
21301                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21302            }
21303        }
21304    }
21305
21306    private void sendPackageChangedBroadcast(String packageName,
21307            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21308        if (DEBUG_INSTALL)
21309            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21310                    + componentNames);
21311        Bundle extras = new Bundle(4);
21312        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21313        String nameList[] = new String[componentNames.size()];
21314        componentNames.toArray(nameList);
21315        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21316        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21317        extras.putInt(Intent.EXTRA_UID, packageUid);
21318        // If this is not reporting a change of the overall package, then only send it
21319        // to registered receivers.  We don't want to launch a swath of apps for every
21320        // little component state change.
21321        final int flags = !componentNames.contains(packageName)
21322                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21323        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21324                new int[] {UserHandle.getUserId(packageUid)});
21325    }
21326
21327    @Override
21328    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21329        if (!sUserManager.exists(userId)) return;
21330        final int callingUid = Binder.getCallingUid();
21331        if (getInstantAppPackageName(callingUid) != null) {
21332            return;
21333        }
21334        final int permission = mContext.checkCallingOrSelfPermission(
21335                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21336        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21337        enforceCrossUserPermission(callingUid, userId,
21338                true /* requireFullPermission */, true /* checkShell */, "stop package");
21339        // writer
21340        synchronized (mPackages) {
21341            final PackageSetting ps = mSettings.mPackages.get(packageName);
21342            if (!filterAppAccessLPr(ps, callingUid, userId)
21343                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21344                            allowedByPermission, callingUid, userId)) {
21345                scheduleWritePackageRestrictionsLocked(userId);
21346            }
21347        }
21348    }
21349
21350    @Override
21351    public String getInstallerPackageName(String packageName) {
21352        final int callingUid = Binder.getCallingUid();
21353        if (getInstantAppPackageName(callingUid) != null) {
21354            return null;
21355        }
21356        // reader
21357        synchronized (mPackages) {
21358            final PackageSetting ps = mSettings.mPackages.get(packageName);
21359            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21360                return null;
21361            }
21362            return mSettings.getInstallerPackageNameLPr(packageName);
21363        }
21364    }
21365
21366    public boolean isOrphaned(String packageName) {
21367        // reader
21368        synchronized (mPackages) {
21369            return mSettings.isOrphaned(packageName);
21370        }
21371    }
21372
21373    @Override
21374    public int getApplicationEnabledSetting(String packageName, int userId) {
21375        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21376        int callingUid = Binder.getCallingUid();
21377        enforceCrossUserPermission(callingUid, userId,
21378                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21379        // reader
21380        synchronized (mPackages) {
21381            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21382                return COMPONENT_ENABLED_STATE_DISABLED;
21383            }
21384            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21385        }
21386    }
21387
21388    @Override
21389    public int getComponentEnabledSetting(ComponentName component, int userId) {
21390        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21391        int callingUid = Binder.getCallingUid();
21392        enforceCrossUserPermission(callingUid, userId,
21393                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21394        synchronized (mPackages) {
21395            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21396                    component, TYPE_UNKNOWN, userId)) {
21397                return COMPONENT_ENABLED_STATE_DISABLED;
21398            }
21399            return mSettings.getComponentEnabledSettingLPr(component, userId);
21400        }
21401    }
21402
21403    @Override
21404    public void enterSafeMode() {
21405        enforceSystemOrRoot("Only the system can request entering safe mode");
21406
21407        if (!mSystemReady) {
21408            mSafeMode = true;
21409        }
21410    }
21411
21412    @Override
21413    public void systemReady() {
21414        enforceSystemOrRoot("Only the system can claim the system is ready");
21415
21416        mSystemReady = true;
21417        final ContentResolver resolver = mContext.getContentResolver();
21418        ContentObserver co = new ContentObserver(mHandler) {
21419            @Override
21420            public void onChange(boolean selfChange) {
21421                mEphemeralAppsDisabled =
21422                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21423                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21424            }
21425        };
21426        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21427                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21428                false, co, UserHandle.USER_SYSTEM);
21429        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21430                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21431        co.onChange(true);
21432
21433        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21434        // disabled after already being started.
21435        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21436                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21437
21438        // Read the compatibilty setting when the system is ready.
21439        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21440                mContext.getContentResolver(),
21441                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21442        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21443        if (DEBUG_SETTINGS) {
21444            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21445        }
21446
21447        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21448
21449        synchronized (mPackages) {
21450            // Verify that all of the preferred activity components actually
21451            // exist.  It is possible for applications to be updated and at
21452            // that point remove a previously declared activity component that
21453            // had been set as a preferred activity.  We try to clean this up
21454            // the next time we encounter that preferred activity, but it is
21455            // possible for the user flow to never be able to return to that
21456            // situation so here we do a sanity check to make sure we haven't
21457            // left any junk around.
21458            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21459            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21460                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21461                removed.clear();
21462                for (PreferredActivity pa : pir.filterSet()) {
21463                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21464                        removed.add(pa);
21465                    }
21466                }
21467                if (removed.size() > 0) {
21468                    for (int r=0; r<removed.size(); r++) {
21469                        PreferredActivity pa = removed.get(r);
21470                        Slog.w(TAG, "Removing dangling preferred activity: "
21471                                + pa.mPref.mComponent);
21472                        pir.removeFilter(pa);
21473                    }
21474                    mSettings.writePackageRestrictionsLPr(
21475                            mSettings.mPreferredActivities.keyAt(i));
21476                }
21477            }
21478
21479            for (int userId : UserManagerService.getInstance().getUserIds()) {
21480                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21481                    grantPermissionsUserIds = ArrayUtils.appendInt(
21482                            grantPermissionsUserIds, userId);
21483                }
21484            }
21485        }
21486        sUserManager.systemReady();
21487
21488        // If we upgraded grant all default permissions before kicking off.
21489        for (int userId : grantPermissionsUserIds) {
21490            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21491        }
21492
21493        // If we did not grant default permissions, we preload from this the
21494        // default permission exceptions lazily to ensure we don't hit the
21495        // disk on a new user creation.
21496        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21497            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21498        }
21499
21500        // Kick off any messages waiting for system ready
21501        if (mPostSystemReadyMessages != null) {
21502            for (Message msg : mPostSystemReadyMessages) {
21503                msg.sendToTarget();
21504            }
21505            mPostSystemReadyMessages = null;
21506        }
21507
21508        // Watch for external volumes that come and go over time
21509        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21510        storage.registerListener(mStorageListener);
21511
21512        mInstallerService.systemReady();
21513        mPackageDexOptimizer.systemReady();
21514
21515        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21516                StorageManagerInternal.class);
21517        StorageManagerInternal.addExternalStoragePolicy(
21518                new StorageManagerInternal.ExternalStorageMountPolicy() {
21519            @Override
21520            public int getMountMode(int uid, String packageName) {
21521                if (Process.isIsolated(uid)) {
21522                    return Zygote.MOUNT_EXTERNAL_NONE;
21523                }
21524                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21525                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21526                }
21527                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21528                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21529                }
21530                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21531                    return Zygote.MOUNT_EXTERNAL_READ;
21532                }
21533                return Zygote.MOUNT_EXTERNAL_WRITE;
21534            }
21535
21536            @Override
21537            public boolean hasExternalStorage(int uid, String packageName) {
21538                return true;
21539            }
21540        });
21541
21542        // Now that we're mostly running, clean up stale users and apps
21543        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21544        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21545
21546        if (mPrivappPermissionsViolations != null) {
21547            Slog.wtf(TAG,"Signature|privileged permissions not in "
21548                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21549            mPrivappPermissionsViolations = null;
21550        }
21551    }
21552
21553    public void waitForAppDataPrepared() {
21554        if (mPrepareAppDataFuture == null) {
21555            return;
21556        }
21557        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21558        mPrepareAppDataFuture = null;
21559    }
21560
21561    @Override
21562    public boolean isSafeMode() {
21563        // allow instant applications
21564        return mSafeMode;
21565    }
21566
21567    @Override
21568    public boolean hasSystemUidErrors() {
21569        // allow instant applications
21570        return mHasSystemUidErrors;
21571    }
21572
21573    static String arrayToString(int[] array) {
21574        StringBuffer buf = new StringBuffer(128);
21575        buf.append('[');
21576        if (array != null) {
21577            for (int i=0; i<array.length; i++) {
21578                if (i > 0) buf.append(", ");
21579                buf.append(array[i]);
21580            }
21581        }
21582        buf.append(']');
21583        return buf.toString();
21584    }
21585
21586    static class DumpState {
21587        public static final int DUMP_LIBS = 1 << 0;
21588        public static final int DUMP_FEATURES = 1 << 1;
21589        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21590        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21591        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21592        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21593        public static final int DUMP_PERMISSIONS = 1 << 6;
21594        public static final int DUMP_PACKAGES = 1 << 7;
21595        public static final int DUMP_SHARED_USERS = 1 << 8;
21596        public static final int DUMP_MESSAGES = 1 << 9;
21597        public static final int DUMP_PROVIDERS = 1 << 10;
21598        public static final int DUMP_VERIFIERS = 1 << 11;
21599        public static final int DUMP_PREFERRED = 1 << 12;
21600        public static final int DUMP_PREFERRED_XML = 1 << 13;
21601        public static final int DUMP_KEYSETS = 1 << 14;
21602        public static final int DUMP_VERSION = 1 << 15;
21603        public static final int DUMP_INSTALLS = 1 << 16;
21604        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21605        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21606        public static final int DUMP_FROZEN = 1 << 19;
21607        public static final int DUMP_DEXOPT = 1 << 20;
21608        public static final int DUMP_COMPILER_STATS = 1 << 21;
21609        public static final int DUMP_CHANGES = 1 << 22;
21610
21611        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21612
21613        private int mTypes;
21614
21615        private int mOptions;
21616
21617        private boolean mTitlePrinted;
21618
21619        private SharedUserSetting mSharedUser;
21620
21621        public boolean isDumping(int type) {
21622            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21623                return true;
21624            }
21625
21626            return (mTypes & type) != 0;
21627        }
21628
21629        public void setDump(int type) {
21630            mTypes |= type;
21631        }
21632
21633        public boolean isOptionEnabled(int option) {
21634            return (mOptions & option) != 0;
21635        }
21636
21637        public void setOptionEnabled(int option) {
21638            mOptions |= option;
21639        }
21640
21641        public boolean onTitlePrinted() {
21642            final boolean printed = mTitlePrinted;
21643            mTitlePrinted = true;
21644            return printed;
21645        }
21646
21647        public boolean getTitlePrinted() {
21648            return mTitlePrinted;
21649        }
21650
21651        public void setTitlePrinted(boolean enabled) {
21652            mTitlePrinted = enabled;
21653        }
21654
21655        public SharedUserSetting getSharedUser() {
21656            return mSharedUser;
21657        }
21658
21659        public void setSharedUser(SharedUserSetting user) {
21660            mSharedUser = user;
21661        }
21662    }
21663
21664    @Override
21665    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21666            FileDescriptor err, String[] args, ShellCallback callback,
21667            ResultReceiver resultReceiver) {
21668        (new PackageManagerShellCommand(this)).exec(
21669                this, in, out, err, args, callback, resultReceiver);
21670    }
21671
21672    @Override
21673    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21674        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21675
21676        DumpState dumpState = new DumpState();
21677        boolean fullPreferred = false;
21678        boolean checkin = false;
21679
21680        String packageName = null;
21681        ArraySet<String> permissionNames = null;
21682
21683        int opti = 0;
21684        while (opti < args.length) {
21685            String opt = args[opti];
21686            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21687                break;
21688            }
21689            opti++;
21690
21691            if ("-a".equals(opt)) {
21692                // Right now we only know how to print all.
21693            } else if ("-h".equals(opt)) {
21694                pw.println("Package manager dump options:");
21695                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21696                pw.println("    --checkin: dump for a checkin");
21697                pw.println("    -f: print details of intent filters");
21698                pw.println("    -h: print this help");
21699                pw.println("  cmd may be one of:");
21700                pw.println("    l[ibraries]: list known shared libraries");
21701                pw.println("    f[eatures]: list device features");
21702                pw.println("    k[eysets]: print known keysets");
21703                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21704                pw.println("    perm[issions]: dump permissions");
21705                pw.println("    permission [name ...]: dump declaration and use of given permission");
21706                pw.println("    pref[erred]: print preferred package settings");
21707                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21708                pw.println("    prov[iders]: dump content providers");
21709                pw.println("    p[ackages]: dump installed packages");
21710                pw.println("    s[hared-users]: dump shared user IDs");
21711                pw.println("    m[essages]: print collected runtime messages");
21712                pw.println("    v[erifiers]: print package verifier info");
21713                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21714                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21715                pw.println("    version: print database version info");
21716                pw.println("    write: write current settings now");
21717                pw.println("    installs: details about install sessions");
21718                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21719                pw.println("    dexopt: dump dexopt state");
21720                pw.println("    compiler-stats: dump compiler statistics");
21721                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21722                pw.println("    <package.name>: info about given package");
21723                return;
21724            } else if ("--checkin".equals(opt)) {
21725                checkin = true;
21726            } else if ("-f".equals(opt)) {
21727                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21728            } else if ("--proto".equals(opt)) {
21729                dumpProto(fd);
21730                return;
21731            } else {
21732                pw.println("Unknown argument: " + opt + "; use -h for help");
21733            }
21734        }
21735
21736        // Is the caller requesting to dump a particular piece of data?
21737        if (opti < args.length) {
21738            String cmd = args[opti];
21739            opti++;
21740            // Is this a package name?
21741            if ("android".equals(cmd) || cmd.contains(".")) {
21742                packageName = cmd;
21743                // When dumping a single package, we always dump all of its
21744                // filter information since the amount of data will be reasonable.
21745                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21746            } else if ("check-permission".equals(cmd)) {
21747                if (opti >= args.length) {
21748                    pw.println("Error: check-permission missing permission argument");
21749                    return;
21750                }
21751                String perm = args[opti];
21752                opti++;
21753                if (opti >= args.length) {
21754                    pw.println("Error: check-permission missing package argument");
21755                    return;
21756                }
21757
21758                String pkg = args[opti];
21759                opti++;
21760                int user = UserHandle.getUserId(Binder.getCallingUid());
21761                if (opti < args.length) {
21762                    try {
21763                        user = Integer.parseInt(args[opti]);
21764                    } catch (NumberFormatException e) {
21765                        pw.println("Error: check-permission user argument is not a number: "
21766                                + args[opti]);
21767                        return;
21768                    }
21769                }
21770
21771                // Normalize package name to handle renamed packages and static libs
21772                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21773
21774                pw.println(checkPermission(perm, pkg, user));
21775                return;
21776            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21777                dumpState.setDump(DumpState.DUMP_LIBS);
21778            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21779                dumpState.setDump(DumpState.DUMP_FEATURES);
21780            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21781                if (opti >= args.length) {
21782                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21783                            | DumpState.DUMP_SERVICE_RESOLVERS
21784                            | DumpState.DUMP_RECEIVER_RESOLVERS
21785                            | DumpState.DUMP_CONTENT_RESOLVERS);
21786                } else {
21787                    while (opti < args.length) {
21788                        String name = args[opti];
21789                        if ("a".equals(name) || "activity".equals(name)) {
21790                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21791                        } else if ("s".equals(name) || "service".equals(name)) {
21792                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21793                        } else if ("r".equals(name) || "receiver".equals(name)) {
21794                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21795                        } else if ("c".equals(name) || "content".equals(name)) {
21796                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21797                        } else {
21798                            pw.println("Error: unknown resolver table type: " + name);
21799                            return;
21800                        }
21801                        opti++;
21802                    }
21803                }
21804            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21805                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21806            } else if ("permission".equals(cmd)) {
21807                if (opti >= args.length) {
21808                    pw.println("Error: permission requires permission name");
21809                    return;
21810                }
21811                permissionNames = new ArraySet<>();
21812                while (opti < args.length) {
21813                    permissionNames.add(args[opti]);
21814                    opti++;
21815                }
21816                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21817                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21818            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21819                dumpState.setDump(DumpState.DUMP_PREFERRED);
21820            } else if ("preferred-xml".equals(cmd)) {
21821                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21822                if (opti < args.length && "--full".equals(args[opti])) {
21823                    fullPreferred = true;
21824                    opti++;
21825                }
21826            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21827                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21828            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21829                dumpState.setDump(DumpState.DUMP_PACKAGES);
21830            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21831                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21832            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21833                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21834            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21835                dumpState.setDump(DumpState.DUMP_MESSAGES);
21836            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21837                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21838            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21839                    || "intent-filter-verifiers".equals(cmd)) {
21840                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21841            } else if ("version".equals(cmd)) {
21842                dumpState.setDump(DumpState.DUMP_VERSION);
21843            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21844                dumpState.setDump(DumpState.DUMP_KEYSETS);
21845            } else if ("installs".equals(cmd)) {
21846                dumpState.setDump(DumpState.DUMP_INSTALLS);
21847            } else if ("frozen".equals(cmd)) {
21848                dumpState.setDump(DumpState.DUMP_FROZEN);
21849            } else if ("dexopt".equals(cmd)) {
21850                dumpState.setDump(DumpState.DUMP_DEXOPT);
21851            } else if ("compiler-stats".equals(cmd)) {
21852                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21853            } else if ("changes".equals(cmd)) {
21854                dumpState.setDump(DumpState.DUMP_CHANGES);
21855            } else if ("write".equals(cmd)) {
21856                synchronized (mPackages) {
21857                    mSettings.writeLPr();
21858                    pw.println("Settings written.");
21859                    return;
21860                }
21861            }
21862        }
21863
21864        if (checkin) {
21865            pw.println("vers,1");
21866        }
21867
21868        // reader
21869        synchronized (mPackages) {
21870            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21871                if (!checkin) {
21872                    if (dumpState.onTitlePrinted())
21873                        pw.println();
21874                    pw.println("Database versions:");
21875                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21876                }
21877            }
21878
21879            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21880                if (!checkin) {
21881                    if (dumpState.onTitlePrinted())
21882                        pw.println();
21883                    pw.println("Verifiers:");
21884                    pw.print("  Required: ");
21885                    pw.print(mRequiredVerifierPackage);
21886                    pw.print(" (uid=");
21887                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21888                            UserHandle.USER_SYSTEM));
21889                    pw.println(")");
21890                } else if (mRequiredVerifierPackage != null) {
21891                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21892                    pw.print(",");
21893                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21894                            UserHandle.USER_SYSTEM));
21895                }
21896            }
21897
21898            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21899                    packageName == null) {
21900                if (mIntentFilterVerifierComponent != null) {
21901                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21902                    if (!checkin) {
21903                        if (dumpState.onTitlePrinted())
21904                            pw.println();
21905                        pw.println("Intent Filter Verifier:");
21906                        pw.print("  Using: ");
21907                        pw.print(verifierPackageName);
21908                        pw.print(" (uid=");
21909                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21910                                UserHandle.USER_SYSTEM));
21911                        pw.println(")");
21912                    } else if (verifierPackageName != null) {
21913                        pw.print("ifv,"); pw.print(verifierPackageName);
21914                        pw.print(",");
21915                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21916                                UserHandle.USER_SYSTEM));
21917                    }
21918                } else {
21919                    pw.println();
21920                    pw.println("No Intent Filter Verifier available!");
21921                }
21922            }
21923
21924            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21925                boolean printedHeader = false;
21926                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21927                while (it.hasNext()) {
21928                    String libName = it.next();
21929                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21930                    if (versionedLib == null) {
21931                        continue;
21932                    }
21933                    final int versionCount = versionedLib.size();
21934                    for (int i = 0; i < versionCount; i++) {
21935                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21936                        if (!checkin) {
21937                            if (!printedHeader) {
21938                                if (dumpState.onTitlePrinted())
21939                                    pw.println();
21940                                pw.println("Libraries:");
21941                                printedHeader = true;
21942                            }
21943                            pw.print("  ");
21944                        } else {
21945                            pw.print("lib,");
21946                        }
21947                        pw.print(libEntry.info.getName());
21948                        if (libEntry.info.isStatic()) {
21949                            pw.print(" version=" + libEntry.info.getVersion());
21950                        }
21951                        if (!checkin) {
21952                            pw.print(" -> ");
21953                        }
21954                        if (libEntry.path != null) {
21955                            pw.print(" (jar) ");
21956                            pw.print(libEntry.path);
21957                        } else {
21958                            pw.print(" (apk) ");
21959                            pw.print(libEntry.apk);
21960                        }
21961                        pw.println();
21962                    }
21963                }
21964            }
21965
21966            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21967                if (dumpState.onTitlePrinted())
21968                    pw.println();
21969                if (!checkin) {
21970                    pw.println("Features:");
21971                }
21972
21973                synchronized (mAvailableFeatures) {
21974                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21975                        if (checkin) {
21976                            pw.print("feat,");
21977                            pw.print(feat.name);
21978                            pw.print(",");
21979                            pw.println(feat.version);
21980                        } else {
21981                            pw.print("  ");
21982                            pw.print(feat.name);
21983                            if (feat.version > 0) {
21984                                pw.print(" version=");
21985                                pw.print(feat.version);
21986                            }
21987                            pw.println();
21988                        }
21989                    }
21990                }
21991            }
21992
21993            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21994                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21995                        : "Activity Resolver Table:", "  ", packageName,
21996                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21997                    dumpState.setTitlePrinted(true);
21998                }
21999            }
22000            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22001                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22002                        : "Receiver Resolver Table:", "  ", packageName,
22003                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22004                    dumpState.setTitlePrinted(true);
22005                }
22006            }
22007            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22008                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22009                        : "Service Resolver Table:", "  ", packageName,
22010                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22011                    dumpState.setTitlePrinted(true);
22012                }
22013            }
22014            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22015                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22016                        : "Provider Resolver Table:", "  ", packageName,
22017                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22018                    dumpState.setTitlePrinted(true);
22019                }
22020            }
22021
22022            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22023                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22024                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22025                    int user = mSettings.mPreferredActivities.keyAt(i);
22026                    if (pir.dump(pw,
22027                            dumpState.getTitlePrinted()
22028                                ? "\nPreferred Activities User " + user + ":"
22029                                : "Preferred Activities User " + user + ":", "  ",
22030                            packageName, true, false)) {
22031                        dumpState.setTitlePrinted(true);
22032                    }
22033                }
22034            }
22035
22036            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22037                pw.flush();
22038                FileOutputStream fout = new FileOutputStream(fd);
22039                BufferedOutputStream str = new BufferedOutputStream(fout);
22040                XmlSerializer serializer = new FastXmlSerializer();
22041                try {
22042                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22043                    serializer.startDocument(null, true);
22044                    serializer.setFeature(
22045                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22046                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22047                    serializer.endDocument();
22048                    serializer.flush();
22049                } catch (IllegalArgumentException e) {
22050                    pw.println("Failed writing: " + e);
22051                } catch (IllegalStateException e) {
22052                    pw.println("Failed writing: " + e);
22053                } catch (IOException e) {
22054                    pw.println("Failed writing: " + e);
22055                }
22056            }
22057
22058            if (!checkin
22059                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22060                    && packageName == null) {
22061                pw.println();
22062                int count = mSettings.mPackages.size();
22063                if (count == 0) {
22064                    pw.println("No applications!");
22065                    pw.println();
22066                } else {
22067                    final String prefix = "  ";
22068                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22069                    if (allPackageSettings.size() == 0) {
22070                        pw.println("No domain preferred apps!");
22071                        pw.println();
22072                    } else {
22073                        pw.println("App verification status:");
22074                        pw.println();
22075                        count = 0;
22076                        for (PackageSetting ps : allPackageSettings) {
22077                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22078                            if (ivi == null || ivi.getPackageName() == null) continue;
22079                            pw.println(prefix + "Package: " + ivi.getPackageName());
22080                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22081                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22082                            pw.println();
22083                            count++;
22084                        }
22085                        if (count == 0) {
22086                            pw.println(prefix + "No app verification established.");
22087                            pw.println();
22088                        }
22089                        for (int userId : sUserManager.getUserIds()) {
22090                            pw.println("App linkages for user " + userId + ":");
22091                            pw.println();
22092                            count = 0;
22093                            for (PackageSetting ps : allPackageSettings) {
22094                                final long status = ps.getDomainVerificationStatusForUser(userId);
22095                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22096                                        && !DEBUG_DOMAIN_VERIFICATION) {
22097                                    continue;
22098                                }
22099                                pw.println(prefix + "Package: " + ps.name);
22100                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22101                                String statusStr = IntentFilterVerificationInfo.
22102                                        getStatusStringFromValue(status);
22103                                pw.println(prefix + "Status:  " + statusStr);
22104                                pw.println();
22105                                count++;
22106                            }
22107                            if (count == 0) {
22108                                pw.println(prefix + "No configured app linkages.");
22109                                pw.println();
22110                            }
22111                        }
22112                    }
22113                }
22114            }
22115
22116            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22117                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22118                if (packageName == null && permissionNames == null) {
22119                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22120                        if (iperm == 0) {
22121                            if (dumpState.onTitlePrinted())
22122                                pw.println();
22123                            pw.println("AppOp Permissions:");
22124                        }
22125                        pw.print("  AppOp Permission ");
22126                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22127                        pw.println(":");
22128                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22129                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22130                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22131                        }
22132                    }
22133                }
22134            }
22135
22136            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22137                boolean printedSomething = false;
22138                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22139                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22140                        continue;
22141                    }
22142                    if (!printedSomething) {
22143                        if (dumpState.onTitlePrinted())
22144                            pw.println();
22145                        pw.println("Registered ContentProviders:");
22146                        printedSomething = true;
22147                    }
22148                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22149                    pw.print("    "); pw.println(p.toString());
22150                }
22151                printedSomething = false;
22152                for (Map.Entry<String, PackageParser.Provider> entry :
22153                        mProvidersByAuthority.entrySet()) {
22154                    PackageParser.Provider p = entry.getValue();
22155                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22156                        continue;
22157                    }
22158                    if (!printedSomething) {
22159                        if (dumpState.onTitlePrinted())
22160                            pw.println();
22161                        pw.println("ContentProvider Authorities:");
22162                        printedSomething = true;
22163                    }
22164                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22165                    pw.print("    "); pw.println(p.toString());
22166                    if (p.info != null && p.info.applicationInfo != null) {
22167                        final String appInfo = p.info.applicationInfo.toString();
22168                        pw.print("      applicationInfo="); pw.println(appInfo);
22169                    }
22170                }
22171            }
22172
22173            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22174                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22175            }
22176
22177            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22178                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22179            }
22180
22181            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22182                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22183            }
22184
22185            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22186                if (dumpState.onTitlePrinted()) pw.println();
22187                pw.println("Package Changes:");
22188                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22189                final int K = mChangedPackages.size();
22190                for (int i = 0; i < K; i++) {
22191                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22192                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22193                    final int N = changes.size();
22194                    if (N == 0) {
22195                        pw.print("    "); pw.println("No packages changed");
22196                    } else {
22197                        for (int j = 0; j < N; j++) {
22198                            final String pkgName = changes.valueAt(j);
22199                            final int sequenceNumber = changes.keyAt(j);
22200                            pw.print("    ");
22201                            pw.print("seq=");
22202                            pw.print(sequenceNumber);
22203                            pw.print(", package=");
22204                            pw.println(pkgName);
22205                        }
22206                    }
22207                }
22208            }
22209
22210            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22211                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22212            }
22213
22214            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22215                // XXX should handle packageName != null by dumping only install data that
22216                // the given package is involved with.
22217                if (dumpState.onTitlePrinted()) pw.println();
22218
22219                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22220                ipw.println();
22221                ipw.println("Frozen packages:");
22222                ipw.increaseIndent();
22223                if (mFrozenPackages.size() == 0) {
22224                    ipw.println("(none)");
22225                } else {
22226                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22227                        ipw.println(mFrozenPackages.valueAt(i));
22228                    }
22229                }
22230                ipw.decreaseIndent();
22231            }
22232
22233            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22234                if (dumpState.onTitlePrinted()) pw.println();
22235                dumpDexoptStateLPr(pw, packageName);
22236            }
22237
22238            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22239                if (dumpState.onTitlePrinted()) pw.println();
22240                dumpCompilerStatsLPr(pw, packageName);
22241            }
22242
22243            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22244                if (dumpState.onTitlePrinted()) pw.println();
22245                mSettings.dumpReadMessagesLPr(pw, dumpState);
22246
22247                pw.println();
22248                pw.println("Package warning messages:");
22249                BufferedReader in = null;
22250                String line = null;
22251                try {
22252                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22253                    while ((line = in.readLine()) != null) {
22254                        if (line.contains("ignored: updated version")) continue;
22255                        pw.println(line);
22256                    }
22257                } catch (IOException ignored) {
22258                } finally {
22259                    IoUtils.closeQuietly(in);
22260                }
22261            }
22262
22263            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22264                BufferedReader in = null;
22265                String line = null;
22266                try {
22267                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22268                    while ((line = in.readLine()) != null) {
22269                        if (line.contains("ignored: updated version")) continue;
22270                        pw.print("msg,");
22271                        pw.println(line);
22272                    }
22273                } catch (IOException ignored) {
22274                } finally {
22275                    IoUtils.closeQuietly(in);
22276                }
22277            }
22278        }
22279
22280        // PackageInstaller should be called outside of mPackages lock
22281        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22282            // XXX should handle packageName != null by dumping only install data that
22283            // the given package is involved with.
22284            if (dumpState.onTitlePrinted()) pw.println();
22285            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22286        }
22287    }
22288
22289    private void dumpProto(FileDescriptor fd) {
22290        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22291
22292        synchronized (mPackages) {
22293            final long requiredVerifierPackageToken =
22294                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22295            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22296            proto.write(
22297                    PackageServiceDumpProto.PackageShortProto.UID,
22298                    getPackageUid(
22299                            mRequiredVerifierPackage,
22300                            MATCH_DEBUG_TRIAGED_MISSING,
22301                            UserHandle.USER_SYSTEM));
22302            proto.end(requiredVerifierPackageToken);
22303
22304            if (mIntentFilterVerifierComponent != null) {
22305                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22306                final long verifierPackageToken =
22307                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22308                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22309                proto.write(
22310                        PackageServiceDumpProto.PackageShortProto.UID,
22311                        getPackageUid(
22312                                verifierPackageName,
22313                                MATCH_DEBUG_TRIAGED_MISSING,
22314                                UserHandle.USER_SYSTEM));
22315                proto.end(verifierPackageToken);
22316            }
22317
22318            dumpSharedLibrariesProto(proto);
22319            dumpFeaturesProto(proto);
22320            mSettings.dumpPackagesProto(proto);
22321            mSettings.dumpSharedUsersProto(proto);
22322            dumpMessagesProto(proto);
22323        }
22324        proto.flush();
22325    }
22326
22327    private void dumpMessagesProto(ProtoOutputStream proto) {
22328        BufferedReader in = null;
22329        String line = null;
22330        try {
22331            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22332            while ((line = in.readLine()) != null) {
22333                if (line.contains("ignored: updated version")) continue;
22334                proto.write(PackageServiceDumpProto.MESSAGES, line);
22335            }
22336        } catch (IOException ignored) {
22337        } finally {
22338            IoUtils.closeQuietly(in);
22339        }
22340    }
22341
22342    private void dumpFeaturesProto(ProtoOutputStream proto) {
22343        synchronized (mAvailableFeatures) {
22344            final int count = mAvailableFeatures.size();
22345            for (int i = 0; i < count; i++) {
22346                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22347                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22348                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22349                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22350                proto.end(featureToken);
22351            }
22352        }
22353    }
22354
22355    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22356        final int count = mSharedLibraries.size();
22357        for (int i = 0; i < count; i++) {
22358            final String libName = mSharedLibraries.keyAt(i);
22359            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22360            if (versionedLib == null) {
22361                continue;
22362            }
22363            final int versionCount = versionedLib.size();
22364            for (int j = 0; j < versionCount; j++) {
22365                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22366                final long sharedLibraryToken =
22367                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22368                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22369                final boolean isJar = (libEntry.path != null);
22370                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22371                if (isJar) {
22372                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22373                } else {
22374                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22375                }
22376                proto.end(sharedLibraryToken);
22377            }
22378        }
22379    }
22380
22381    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22382        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22383        ipw.println();
22384        ipw.println("Dexopt state:");
22385        ipw.increaseIndent();
22386        Collection<PackageParser.Package> packages = null;
22387        if (packageName != null) {
22388            PackageParser.Package targetPackage = mPackages.get(packageName);
22389            if (targetPackage != null) {
22390                packages = Collections.singletonList(targetPackage);
22391            } else {
22392                ipw.println("Unable to find package: " + packageName);
22393                return;
22394            }
22395        } else {
22396            packages = mPackages.values();
22397        }
22398
22399        for (PackageParser.Package pkg : packages) {
22400            ipw.println("[" + pkg.packageName + "]");
22401            ipw.increaseIndent();
22402            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22403            ipw.decreaseIndent();
22404        }
22405    }
22406
22407    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22408        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22409        ipw.println();
22410        ipw.println("Compiler stats:");
22411        ipw.increaseIndent();
22412        Collection<PackageParser.Package> packages = null;
22413        if (packageName != null) {
22414            PackageParser.Package targetPackage = mPackages.get(packageName);
22415            if (targetPackage != null) {
22416                packages = Collections.singletonList(targetPackage);
22417            } else {
22418                ipw.println("Unable to find package: " + packageName);
22419                return;
22420            }
22421        } else {
22422            packages = mPackages.values();
22423        }
22424
22425        for (PackageParser.Package pkg : packages) {
22426            ipw.println("[" + pkg.packageName + "]");
22427            ipw.increaseIndent();
22428
22429            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22430            if (stats == null) {
22431                ipw.println("(No recorded stats)");
22432            } else {
22433                stats.dump(ipw);
22434            }
22435            ipw.decreaseIndent();
22436        }
22437    }
22438
22439    private String dumpDomainString(String packageName) {
22440        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22441                .getList();
22442        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22443
22444        ArraySet<String> result = new ArraySet<>();
22445        if (iviList.size() > 0) {
22446            for (IntentFilterVerificationInfo ivi : iviList) {
22447                for (String host : ivi.getDomains()) {
22448                    result.add(host);
22449                }
22450            }
22451        }
22452        if (filters != null && filters.size() > 0) {
22453            for (IntentFilter filter : filters) {
22454                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22455                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22456                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22457                    result.addAll(filter.getHostsList());
22458                }
22459            }
22460        }
22461
22462        StringBuilder sb = new StringBuilder(result.size() * 16);
22463        for (String domain : result) {
22464            if (sb.length() > 0) sb.append(" ");
22465            sb.append(domain);
22466        }
22467        return sb.toString();
22468    }
22469
22470    // ------- apps on sdcard specific code -------
22471    static final boolean DEBUG_SD_INSTALL = false;
22472
22473    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22474
22475    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22476
22477    private boolean mMediaMounted = false;
22478
22479    static String getEncryptKey() {
22480        try {
22481            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22482                    SD_ENCRYPTION_KEYSTORE_NAME);
22483            if (sdEncKey == null) {
22484                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22485                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22486                if (sdEncKey == null) {
22487                    Slog.e(TAG, "Failed to create encryption keys");
22488                    return null;
22489                }
22490            }
22491            return sdEncKey;
22492        } catch (NoSuchAlgorithmException nsae) {
22493            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22494            return null;
22495        } catch (IOException ioe) {
22496            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22497            return null;
22498        }
22499    }
22500
22501    /*
22502     * Update media status on PackageManager.
22503     */
22504    @Override
22505    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22506        enforceSystemOrRoot("Media status can only be updated by the system");
22507        // reader; this apparently protects mMediaMounted, but should probably
22508        // be a different lock in that case.
22509        synchronized (mPackages) {
22510            Log.i(TAG, "Updating external media status from "
22511                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22512                    + (mediaStatus ? "mounted" : "unmounted"));
22513            if (DEBUG_SD_INSTALL)
22514                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22515                        + ", mMediaMounted=" + mMediaMounted);
22516            if (mediaStatus == mMediaMounted) {
22517                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22518                        : 0, -1);
22519                mHandler.sendMessage(msg);
22520                return;
22521            }
22522            mMediaMounted = mediaStatus;
22523        }
22524        // Queue up an async operation since the package installation may take a
22525        // little while.
22526        mHandler.post(new Runnable() {
22527            public void run() {
22528                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22529            }
22530        });
22531    }
22532
22533    /**
22534     * Called by StorageManagerService when the initial ASECs to scan are available.
22535     * Should block until all the ASEC containers are finished being scanned.
22536     */
22537    public void scanAvailableAsecs() {
22538        updateExternalMediaStatusInner(true, false, false);
22539    }
22540
22541    /*
22542     * Collect information of applications on external media, map them against
22543     * existing containers and update information based on current mount status.
22544     * Please note that we always have to report status if reportStatus has been
22545     * set to true especially when unloading packages.
22546     */
22547    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22548            boolean externalStorage) {
22549        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22550        int[] uidArr = EmptyArray.INT;
22551
22552        final String[] list = PackageHelper.getSecureContainerList();
22553        if (ArrayUtils.isEmpty(list)) {
22554            Log.i(TAG, "No secure containers found");
22555        } else {
22556            // Process list of secure containers and categorize them
22557            // as active or stale based on their package internal state.
22558
22559            // reader
22560            synchronized (mPackages) {
22561                for (String cid : list) {
22562                    // Leave stages untouched for now; installer service owns them
22563                    if (PackageInstallerService.isStageName(cid)) continue;
22564
22565                    if (DEBUG_SD_INSTALL)
22566                        Log.i(TAG, "Processing container " + cid);
22567                    String pkgName = getAsecPackageName(cid);
22568                    if (pkgName == null) {
22569                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22570                        continue;
22571                    }
22572                    if (DEBUG_SD_INSTALL)
22573                        Log.i(TAG, "Looking for pkg : " + pkgName);
22574
22575                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22576                    if (ps == null) {
22577                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22578                        continue;
22579                    }
22580
22581                    /*
22582                     * Skip packages that are not external if we're unmounting
22583                     * external storage.
22584                     */
22585                    if (externalStorage && !isMounted && !isExternal(ps)) {
22586                        continue;
22587                    }
22588
22589                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22590                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22591                    // The package status is changed only if the code path
22592                    // matches between settings and the container id.
22593                    if (ps.codePathString != null
22594                            && ps.codePathString.startsWith(args.getCodePath())) {
22595                        if (DEBUG_SD_INSTALL) {
22596                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22597                                    + " at code path: " + ps.codePathString);
22598                        }
22599
22600                        // We do have a valid package installed on sdcard
22601                        processCids.put(args, ps.codePathString);
22602                        final int uid = ps.appId;
22603                        if (uid != -1) {
22604                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22605                        }
22606                    } else {
22607                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22608                                + ps.codePathString);
22609                    }
22610                }
22611            }
22612
22613            Arrays.sort(uidArr);
22614        }
22615
22616        // Process packages with valid entries.
22617        if (isMounted) {
22618            if (DEBUG_SD_INSTALL)
22619                Log.i(TAG, "Loading packages");
22620            loadMediaPackages(processCids, uidArr, externalStorage);
22621            startCleaningPackages();
22622            mInstallerService.onSecureContainersAvailable();
22623        } else {
22624            if (DEBUG_SD_INSTALL)
22625                Log.i(TAG, "Unloading packages");
22626            unloadMediaPackages(processCids, uidArr, reportStatus);
22627        }
22628    }
22629
22630    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22631            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22632        final int size = infos.size();
22633        final String[] packageNames = new String[size];
22634        final int[] packageUids = new int[size];
22635        for (int i = 0; i < size; i++) {
22636            final ApplicationInfo info = infos.get(i);
22637            packageNames[i] = info.packageName;
22638            packageUids[i] = info.uid;
22639        }
22640        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22641                finishedReceiver);
22642    }
22643
22644    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22645            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22646        sendResourcesChangedBroadcast(mediaStatus, replacing,
22647                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22648    }
22649
22650    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22651            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22652        int size = pkgList.length;
22653        if (size > 0) {
22654            // Send broadcasts here
22655            Bundle extras = new Bundle();
22656            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22657            if (uidArr != null) {
22658                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22659            }
22660            if (replacing) {
22661                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22662            }
22663            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22664                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22665            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22666        }
22667    }
22668
22669   /*
22670     * Look at potentially valid container ids from processCids If package
22671     * information doesn't match the one on record or package scanning fails,
22672     * the cid is added to list of removeCids. We currently don't delete stale
22673     * containers.
22674     */
22675    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22676            boolean externalStorage) {
22677        ArrayList<String> pkgList = new ArrayList<String>();
22678        Set<AsecInstallArgs> keys = processCids.keySet();
22679
22680        for (AsecInstallArgs args : keys) {
22681            String codePath = processCids.get(args);
22682            if (DEBUG_SD_INSTALL)
22683                Log.i(TAG, "Loading container : " + args.cid);
22684            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22685            try {
22686                // Make sure there are no container errors first.
22687                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22688                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22689                            + " when installing from sdcard");
22690                    continue;
22691                }
22692                // Check code path here.
22693                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22694                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22695                            + " does not match one in settings " + codePath);
22696                    continue;
22697                }
22698                // Parse package
22699                int parseFlags = mDefParseFlags;
22700                if (args.isExternalAsec()) {
22701                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22702                }
22703                if (args.isFwdLocked()) {
22704                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22705                }
22706
22707                synchronized (mInstallLock) {
22708                    PackageParser.Package pkg = null;
22709                    try {
22710                        // Sadly we don't know the package name yet to freeze it
22711                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22712                                SCAN_IGNORE_FROZEN, 0, null);
22713                    } catch (PackageManagerException e) {
22714                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22715                    }
22716                    // Scan the package
22717                    if (pkg != null) {
22718                        /*
22719                         * TODO why is the lock being held? doPostInstall is
22720                         * called in other places without the lock. This needs
22721                         * to be straightened out.
22722                         */
22723                        // writer
22724                        synchronized (mPackages) {
22725                            retCode = PackageManager.INSTALL_SUCCEEDED;
22726                            pkgList.add(pkg.packageName);
22727                            // Post process args
22728                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22729                                    pkg.applicationInfo.uid);
22730                        }
22731                    } else {
22732                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22733                    }
22734                }
22735
22736            } finally {
22737                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22738                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22739                }
22740            }
22741        }
22742        // writer
22743        synchronized (mPackages) {
22744            // If the platform SDK has changed since the last time we booted,
22745            // we need to re-grant app permission to catch any new ones that
22746            // appear. This is really a hack, and means that apps can in some
22747            // cases get permissions that the user didn't initially explicitly
22748            // allow... it would be nice to have some better way to handle
22749            // this situation.
22750            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22751                    : mSettings.getInternalVersion();
22752            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22753                    : StorageManager.UUID_PRIVATE_INTERNAL;
22754
22755            int updateFlags = UPDATE_PERMISSIONS_ALL;
22756            if (ver.sdkVersion != mSdkVersion) {
22757                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22758                        + mSdkVersion + "; regranting permissions for external");
22759                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22760            }
22761            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22762
22763            // Yay, everything is now upgraded
22764            ver.forceCurrent();
22765
22766            // can downgrade to reader
22767            // Persist settings
22768            mSettings.writeLPr();
22769        }
22770        // Send a broadcast to let everyone know we are done processing
22771        if (pkgList.size() > 0) {
22772            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22773        }
22774    }
22775
22776   /*
22777     * Utility method to unload a list of specified containers
22778     */
22779    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22780        // Just unmount all valid containers.
22781        for (AsecInstallArgs arg : cidArgs) {
22782            synchronized (mInstallLock) {
22783                arg.doPostDeleteLI(false);
22784           }
22785       }
22786   }
22787
22788    /*
22789     * Unload packages mounted on external media. This involves deleting package
22790     * data from internal structures, sending broadcasts about disabled packages,
22791     * gc'ing to free up references, unmounting all secure containers
22792     * corresponding to packages on external media, and posting a
22793     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22794     * that we always have to post this message if status has been requested no
22795     * matter what.
22796     */
22797    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22798            final boolean reportStatus) {
22799        if (DEBUG_SD_INSTALL)
22800            Log.i(TAG, "unloading media packages");
22801        ArrayList<String> pkgList = new ArrayList<String>();
22802        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22803        final Set<AsecInstallArgs> keys = processCids.keySet();
22804        for (AsecInstallArgs args : keys) {
22805            String pkgName = args.getPackageName();
22806            if (DEBUG_SD_INSTALL)
22807                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22808            // Delete package internally
22809            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22810            synchronized (mInstallLock) {
22811                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22812                final boolean res;
22813                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22814                        "unloadMediaPackages")) {
22815                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22816                            null);
22817                }
22818                if (res) {
22819                    pkgList.add(pkgName);
22820                } else {
22821                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22822                    failedList.add(args);
22823                }
22824            }
22825        }
22826
22827        // reader
22828        synchronized (mPackages) {
22829            // We didn't update the settings after removing each package;
22830            // write them now for all packages.
22831            mSettings.writeLPr();
22832        }
22833
22834        // We have to absolutely send UPDATED_MEDIA_STATUS only
22835        // after confirming that all the receivers processed the ordered
22836        // broadcast when packages get disabled, force a gc to clean things up.
22837        // and unload all the containers.
22838        if (pkgList.size() > 0) {
22839            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22840                    new IIntentReceiver.Stub() {
22841                public void performReceive(Intent intent, int resultCode, String data,
22842                        Bundle extras, boolean ordered, boolean sticky,
22843                        int sendingUser) throws RemoteException {
22844                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22845                            reportStatus ? 1 : 0, 1, keys);
22846                    mHandler.sendMessage(msg);
22847                }
22848            });
22849        } else {
22850            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22851                    keys);
22852            mHandler.sendMessage(msg);
22853        }
22854    }
22855
22856    private void loadPrivatePackages(final VolumeInfo vol) {
22857        mHandler.post(new Runnable() {
22858            @Override
22859            public void run() {
22860                loadPrivatePackagesInner(vol);
22861            }
22862        });
22863    }
22864
22865    private void loadPrivatePackagesInner(VolumeInfo vol) {
22866        final String volumeUuid = vol.fsUuid;
22867        if (TextUtils.isEmpty(volumeUuid)) {
22868            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22869            return;
22870        }
22871
22872        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22873        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22874        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22875
22876        final VersionInfo ver;
22877        final List<PackageSetting> packages;
22878        synchronized (mPackages) {
22879            ver = mSettings.findOrCreateVersion(volumeUuid);
22880            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22881        }
22882
22883        for (PackageSetting ps : packages) {
22884            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22885            synchronized (mInstallLock) {
22886                final PackageParser.Package pkg;
22887                try {
22888                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22889                    loaded.add(pkg.applicationInfo);
22890
22891                } catch (PackageManagerException e) {
22892                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22893                }
22894
22895                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22896                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22897                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22898                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22899                }
22900            }
22901        }
22902
22903        // Reconcile app data for all started/unlocked users
22904        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22905        final UserManager um = mContext.getSystemService(UserManager.class);
22906        UserManagerInternal umInternal = getUserManagerInternal();
22907        for (UserInfo user : um.getUsers()) {
22908            final int flags;
22909            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22910                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22911            } else if (umInternal.isUserRunning(user.id)) {
22912                flags = StorageManager.FLAG_STORAGE_DE;
22913            } else {
22914                continue;
22915            }
22916
22917            try {
22918                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22919                synchronized (mInstallLock) {
22920                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22921                }
22922            } catch (IllegalStateException e) {
22923                // Device was probably ejected, and we'll process that event momentarily
22924                Slog.w(TAG, "Failed to prepare storage: " + e);
22925            }
22926        }
22927
22928        synchronized (mPackages) {
22929            int updateFlags = UPDATE_PERMISSIONS_ALL;
22930            if (ver.sdkVersion != mSdkVersion) {
22931                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22932                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22933                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22934            }
22935            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22936
22937            // Yay, everything is now upgraded
22938            ver.forceCurrent();
22939
22940            mSettings.writeLPr();
22941        }
22942
22943        for (PackageFreezer freezer : freezers) {
22944            freezer.close();
22945        }
22946
22947        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22948        sendResourcesChangedBroadcast(true, false, loaded, null);
22949    }
22950
22951    private void unloadPrivatePackages(final VolumeInfo vol) {
22952        mHandler.post(new Runnable() {
22953            @Override
22954            public void run() {
22955                unloadPrivatePackagesInner(vol);
22956            }
22957        });
22958    }
22959
22960    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22961        final String volumeUuid = vol.fsUuid;
22962        if (TextUtils.isEmpty(volumeUuid)) {
22963            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22964            return;
22965        }
22966
22967        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22968        synchronized (mInstallLock) {
22969        synchronized (mPackages) {
22970            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22971            for (PackageSetting ps : packages) {
22972                if (ps.pkg == null) continue;
22973
22974                final ApplicationInfo info = ps.pkg.applicationInfo;
22975                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22976                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22977
22978                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22979                        "unloadPrivatePackagesInner")) {
22980                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22981                            false, null)) {
22982                        unloaded.add(info);
22983                    } else {
22984                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22985                    }
22986                }
22987
22988                // Try very hard to release any references to this package
22989                // so we don't risk the system server being killed due to
22990                // open FDs
22991                AttributeCache.instance().removePackage(ps.name);
22992            }
22993
22994            mSettings.writeLPr();
22995        }
22996        }
22997
22998        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22999        sendResourcesChangedBroadcast(false, false, unloaded, null);
23000
23001        // Try very hard to release any references to this path so we don't risk
23002        // the system server being killed due to open FDs
23003        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23004
23005        for (int i = 0; i < 3; i++) {
23006            System.gc();
23007            System.runFinalization();
23008        }
23009    }
23010
23011    private void assertPackageKnown(String volumeUuid, String packageName)
23012            throws PackageManagerException {
23013        synchronized (mPackages) {
23014            // Normalize package name to handle renamed packages
23015            packageName = normalizePackageNameLPr(packageName);
23016
23017            final PackageSetting ps = mSettings.mPackages.get(packageName);
23018            if (ps == null) {
23019                throw new PackageManagerException("Package " + packageName + " is unknown");
23020            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23021                throw new PackageManagerException(
23022                        "Package " + packageName + " found on unknown volume " + volumeUuid
23023                                + "; expected volume " + ps.volumeUuid);
23024            }
23025        }
23026    }
23027
23028    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23029            throws PackageManagerException {
23030        synchronized (mPackages) {
23031            // Normalize package name to handle renamed packages
23032            packageName = normalizePackageNameLPr(packageName);
23033
23034            final PackageSetting ps = mSettings.mPackages.get(packageName);
23035            if (ps == null) {
23036                throw new PackageManagerException("Package " + packageName + " is unknown");
23037            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23038                throw new PackageManagerException(
23039                        "Package " + packageName + " found on unknown volume " + volumeUuid
23040                                + "; expected volume " + ps.volumeUuid);
23041            } else if (!ps.getInstalled(userId)) {
23042                throw new PackageManagerException(
23043                        "Package " + packageName + " not installed for user " + userId);
23044            }
23045        }
23046    }
23047
23048    private List<String> collectAbsoluteCodePaths() {
23049        synchronized (mPackages) {
23050            List<String> codePaths = new ArrayList<>();
23051            final int packageCount = mSettings.mPackages.size();
23052            for (int i = 0; i < packageCount; i++) {
23053                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23054                codePaths.add(ps.codePath.getAbsolutePath());
23055            }
23056            return codePaths;
23057        }
23058    }
23059
23060    /**
23061     * Examine all apps present on given mounted volume, and destroy apps that
23062     * aren't expected, either due to uninstallation or reinstallation on
23063     * another volume.
23064     */
23065    private void reconcileApps(String volumeUuid) {
23066        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23067        List<File> filesToDelete = null;
23068
23069        final File[] files = FileUtils.listFilesOrEmpty(
23070                Environment.getDataAppDirectory(volumeUuid));
23071        for (File file : files) {
23072            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23073                    && !PackageInstallerService.isStageName(file.getName());
23074            if (!isPackage) {
23075                // Ignore entries which are not packages
23076                continue;
23077            }
23078
23079            String absolutePath = file.getAbsolutePath();
23080
23081            boolean pathValid = false;
23082            final int absoluteCodePathCount = absoluteCodePaths.size();
23083            for (int i = 0; i < absoluteCodePathCount; i++) {
23084                String absoluteCodePath = absoluteCodePaths.get(i);
23085                if (absolutePath.startsWith(absoluteCodePath)) {
23086                    pathValid = true;
23087                    break;
23088                }
23089            }
23090
23091            if (!pathValid) {
23092                if (filesToDelete == null) {
23093                    filesToDelete = new ArrayList<>();
23094                }
23095                filesToDelete.add(file);
23096            }
23097        }
23098
23099        if (filesToDelete != null) {
23100            final int fileToDeleteCount = filesToDelete.size();
23101            for (int i = 0; i < fileToDeleteCount; i++) {
23102                File fileToDelete = filesToDelete.get(i);
23103                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23104                synchronized (mInstallLock) {
23105                    removeCodePathLI(fileToDelete);
23106                }
23107            }
23108        }
23109    }
23110
23111    /**
23112     * Reconcile all app data for the given user.
23113     * <p>
23114     * Verifies that directories exist and that ownership and labeling is
23115     * correct for all installed apps on all mounted volumes.
23116     */
23117    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23118        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23119        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23120            final String volumeUuid = vol.getFsUuid();
23121            synchronized (mInstallLock) {
23122                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23123            }
23124        }
23125    }
23126
23127    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23128            boolean migrateAppData) {
23129        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23130    }
23131
23132    /**
23133     * Reconcile all app data on given mounted volume.
23134     * <p>
23135     * Destroys app data that isn't expected, either due to uninstallation or
23136     * reinstallation on another volume.
23137     * <p>
23138     * Verifies that directories exist and that ownership and labeling is
23139     * correct for all installed apps.
23140     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23141     */
23142    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23143            boolean migrateAppData, boolean onlyCoreApps) {
23144        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23145                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23146        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23147
23148        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23149        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23150
23151        // First look for stale data that doesn't belong, and check if things
23152        // have changed since we did our last restorecon
23153        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23154            if (StorageManager.isFileEncryptedNativeOrEmulated()
23155                    && !StorageManager.isUserKeyUnlocked(userId)) {
23156                throw new RuntimeException(
23157                        "Yikes, someone asked us to reconcile CE storage while " + userId
23158                                + " was still locked; this would have caused massive data loss!");
23159            }
23160
23161            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23162            for (File file : files) {
23163                final String packageName = file.getName();
23164                try {
23165                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23166                } catch (PackageManagerException e) {
23167                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23168                    try {
23169                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23170                                StorageManager.FLAG_STORAGE_CE, 0);
23171                    } catch (InstallerException e2) {
23172                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23173                    }
23174                }
23175            }
23176        }
23177        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23178            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23179            for (File file : files) {
23180                final String packageName = file.getName();
23181                try {
23182                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23183                } catch (PackageManagerException e) {
23184                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23185                    try {
23186                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23187                                StorageManager.FLAG_STORAGE_DE, 0);
23188                    } catch (InstallerException e2) {
23189                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23190                    }
23191                }
23192            }
23193        }
23194
23195        // Ensure that data directories are ready to roll for all packages
23196        // installed for this volume and user
23197        final List<PackageSetting> packages;
23198        synchronized (mPackages) {
23199            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23200        }
23201        int preparedCount = 0;
23202        for (PackageSetting ps : packages) {
23203            final String packageName = ps.name;
23204            if (ps.pkg == null) {
23205                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23206                // TODO: might be due to legacy ASEC apps; we should circle back
23207                // and reconcile again once they're scanned
23208                continue;
23209            }
23210            // Skip non-core apps if requested
23211            if (onlyCoreApps && !ps.pkg.coreApp) {
23212                result.add(packageName);
23213                continue;
23214            }
23215
23216            if (ps.getInstalled(userId)) {
23217                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23218                preparedCount++;
23219            }
23220        }
23221
23222        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23223        return result;
23224    }
23225
23226    /**
23227     * Prepare app data for the given app just after it was installed or
23228     * upgraded. This method carefully only touches users that it's installed
23229     * for, and it forces a restorecon to handle any seinfo changes.
23230     * <p>
23231     * Verifies that directories exist and that ownership and labeling is
23232     * correct for all installed apps. If there is an ownership mismatch, it
23233     * will try recovering system apps by wiping data; third-party app data is
23234     * left intact.
23235     * <p>
23236     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23237     */
23238    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23239        final PackageSetting ps;
23240        synchronized (mPackages) {
23241            ps = mSettings.mPackages.get(pkg.packageName);
23242            mSettings.writeKernelMappingLPr(ps);
23243        }
23244
23245        final UserManager um = mContext.getSystemService(UserManager.class);
23246        UserManagerInternal umInternal = getUserManagerInternal();
23247        for (UserInfo user : um.getUsers()) {
23248            final int flags;
23249            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23250                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23251            } else if (umInternal.isUserRunning(user.id)) {
23252                flags = StorageManager.FLAG_STORAGE_DE;
23253            } else {
23254                continue;
23255            }
23256
23257            if (ps.getInstalled(user.id)) {
23258                // TODO: when user data is locked, mark that we're still dirty
23259                prepareAppDataLIF(pkg, user.id, flags);
23260            }
23261        }
23262    }
23263
23264    /**
23265     * Prepare app data for the given app.
23266     * <p>
23267     * Verifies that directories exist and that ownership and labeling is
23268     * correct for all installed apps. If there is an ownership mismatch, this
23269     * will try recovering system apps by wiping data; third-party app data is
23270     * left intact.
23271     */
23272    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23273        if (pkg == null) {
23274            Slog.wtf(TAG, "Package was null!", new Throwable());
23275            return;
23276        }
23277        prepareAppDataLeafLIF(pkg, userId, flags);
23278        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23279        for (int i = 0; i < childCount; i++) {
23280            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23281        }
23282    }
23283
23284    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23285            boolean maybeMigrateAppData) {
23286        prepareAppDataLIF(pkg, userId, flags);
23287
23288        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23289            // We may have just shuffled around app data directories, so
23290            // prepare them one more time
23291            prepareAppDataLIF(pkg, userId, flags);
23292        }
23293    }
23294
23295    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23296        if (DEBUG_APP_DATA) {
23297            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23298                    + Integer.toHexString(flags));
23299        }
23300
23301        final String volumeUuid = pkg.volumeUuid;
23302        final String packageName = pkg.packageName;
23303        final ApplicationInfo app = pkg.applicationInfo;
23304        final int appId = UserHandle.getAppId(app.uid);
23305
23306        Preconditions.checkNotNull(app.seInfo);
23307
23308        long ceDataInode = -1;
23309        try {
23310            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23311                    appId, app.seInfo, app.targetSdkVersion);
23312        } catch (InstallerException e) {
23313            if (app.isSystemApp()) {
23314                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23315                        + ", but trying to recover: " + e);
23316                destroyAppDataLeafLIF(pkg, userId, flags);
23317                try {
23318                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23319                            appId, app.seInfo, app.targetSdkVersion);
23320                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23321                } catch (InstallerException e2) {
23322                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23323                }
23324            } else {
23325                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23326            }
23327        }
23328
23329        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23330            // TODO: mark this structure as dirty so we persist it!
23331            synchronized (mPackages) {
23332                final PackageSetting ps = mSettings.mPackages.get(packageName);
23333                if (ps != null) {
23334                    ps.setCeDataInode(ceDataInode, userId);
23335                }
23336            }
23337        }
23338
23339        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23340    }
23341
23342    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23343        if (pkg == null) {
23344            Slog.wtf(TAG, "Package was null!", new Throwable());
23345            return;
23346        }
23347        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23348        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23349        for (int i = 0; i < childCount; i++) {
23350            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23351        }
23352    }
23353
23354    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23355        final String volumeUuid = pkg.volumeUuid;
23356        final String packageName = pkg.packageName;
23357        final ApplicationInfo app = pkg.applicationInfo;
23358
23359        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23360            // Create a native library symlink only if we have native libraries
23361            // and if the native libraries are 32 bit libraries. We do not provide
23362            // this symlink for 64 bit libraries.
23363            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23364                final String nativeLibPath = app.nativeLibraryDir;
23365                try {
23366                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23367                            nativeLibPath, userId);
23368                } catch (InstallerException e) {
23369                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23370                }
23371            }
23372        }
23373    }
23374
23375    /**
23376     * For system apps on non-FBE devices, this method migrates any existing
23377     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23378     * requested by the app.
23379     */
23380    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23381        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23382                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23383            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23384                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23385            try {
23386                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23387                        storageTarget);
23388            } catch (InstallerException e) {
23389                logCriticalInfo(Log.WARN,
23390                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23391            }
23392            return true;
23393        } else {
23394            return false;
23395        }
23396    }
23397
23398    public PackageFreezer freezePackage(String packageName, String killReason) {
23399        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23400    }
23401
23402    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23403        return new PackageFreezer(packageName, userId, killReason);
23404    }
23405
23406    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23407            String killReason) {
23408        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23409    }
23410
23411    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23412            String killReason) {
23413        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23414            return new PackageFreezer();
23415        } else {
23416            return freezePackage(packageName, userId, killReason);
23417        }
23418    }
23419
23420    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23421            String killReason) {
23422        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23423    }
23424
23425    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23426            String killReason) {
23427        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23428            return new PackageFreezer();
23429        } else {
23430            return freezePackage(packageName, userId, killReason);
23431        }
23432    }
23433
23434    /**
23435     * Class that freezes and kills the given package upon creation, and
23436     * unfreezes it upon closing. This is typically used when doing surgery on
23437     * app code/data to prevent the app from running while you're working.
23438     */
23439    private class PackageFreezer implements AutoCloseable {
23440        private final String mPackageName;
23441        private final PackageFreezer[] mChildren;
23442
23443        private final boolean mWeFroze;
23444
23445        private final AtomicBoolean mClosed = new AtomicBoolean();
23446        private final CloseGuard mCloseGuard = CloseGuard.get();
23447
23448        /**
23449         * Create and return a stub freezer that doesn't actually do anything,
23450         * typically used when someone requested
23451         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23452         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23453         */
23454        public PackageFreezer() {
23455            mPackageName = null;
23456            mChildren = null;
23457            mWeFroze = false;
23458            mCloseGuard.open("close");
23459        }
23460
23461        public PackageFreezer(String packageName, int userId, String killReason) {
23462            synchronized (mPackages) {
23463                mPackageName = packageName;
23464                mWeFroze = mFrozenPackages.add(mPackageName);
23465
23466                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23467                if (ps != null) {
23468                    killApplication(ps.name, ps.appId, userId, killReason);
23469                }
23470
23471                final PackageParser.Package p = mPackages.get(packageName);
23472                if (p != null && p.childPackages != null) {
23473                    final int N = p.childPackages.size();
23474                    mChildren = new PackageFreezer[N];
23475                    for (int i = 0; i < N; i++) {
23476                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23477                                userId, killReason);
23478                    }
23479                } else {
23480                    mChildren = null;
23481                }
23482            }
23483            mCloseGuard.open("close");
23484        }
23485
23486        @Override
23487        protected void finalize() throws Throwable {
23488            try {
23489                mCloseGuard.warnIfOpen();
23490                close();
23491            } finally {
23492                super.finalize();
23493            }
23494        }
23495
23496        @Override
23497        public void close() {
23498            mCloseGuard.close();
23499            if (mClosed.compareAndSet(false, true)) {
23500                synchronized (mPackages) {
23501                    if (mWeFroze) {
23502                        mFrozenPackages.remove(mPackageName);
23503                    }
23504
23505                    if (mChildren != null) {
23506                        for (PackageFreezer freezer : mChildren) {
23507                            freezer.close();
23508                        }
23509                    }
23510                }
23511            }
23512        }
23513    }
23514
23515    /**
23516     * Verify that given package is currently frozen.
23517     */
23518    private void checkPackageFrozen(String packageName) {
23519        synchronized (mPackages) {
23520            if (!mFrozenPackages.contains(packageName)) {
23521                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23522            }
23523        }
23524    }
23525
23526    @Override
23527    public int movePackage(final String packageName, final String volumeUuid) {
23528        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23529
23530        final int callingUid = Binder.getCallingUid();
23531        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23532        final int moveId = mNextMoveId.getAndIncrement();
23533        mHandler.post(new Runnable() {
23534            @Override
23535            public void run() {
23536                try {
23537                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23538                } catch (PackageManagerException e) {
23539                    Slog.w(TAG, "Failed to move " + packageName, e);
23540                    mMoveCallbacks.notifyStatusChanged(moveId,
23541                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23542                }
23543            }
23544        });
23545        return moveId;
23546    }
23547
23548    private void movePackageInternal(final String packageName, final String volumeUuid,
23549            final int moveId, final int callingUid, UserHandle user)
23550                    throws PackageManagerException {
23551        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23552        final PackageManager pm = mContext.getPackageManager();
23553
23554        final boolean currentAsec;
23555        final String currentVolumeUuid;
23556        final File codeFile;
23557        final String installerPackageName;
23558        final String packageAbiOverride;
23559        final int appId;
23560        final String seinfo;
23561        final String label;
23562        final int targetSdkVersion;
23563        final PackageFreezer freezer;
23564        final int[] installedUserIds;
23565
23566        // reader
23567        synchronized (mPackages) {
23568            final PackageParser.Package pkg = mPackages.get(packageName);
23569            final PackageSetting ps = mSettings.mPackages.get(packageName);
23570            if (pkg == null
23571                    || ps == null
23572                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23573                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23574            }
23575            if (pkg.applicationInfo.isSystemApp()) {
23576                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23577                        "Cannot move system application");
23578            }
23579
23580            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23581            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23582                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23583            if (isInternalStorage && !allow3rdPartyOnInternal) {
23584                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23585                        "3rd party apps are not allowed on internal storage");
23586            }
23587
23588            if (pkg.applicationInfo.isExternalAsec()) {
23589                currentAsec = true;
23590                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23591            } else if (pkg.applicationInfo.isForwardLocked()) {
23592                currentAsec = true;
23593                currentVolumeUuid = "forward_locked";
23594            } else {
23595                currentAsec = false;
23596                currentVolumeUuid = ps.volumeUuid;
23597
23598                final File probe = new File(pkg.codePath);
23599                final File probeOat = new File(probe, "oat");
23600                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23601                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23602                            "Move only supported for modern cluster style installs");
23603                }
23604            }
23605
23606            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23607                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23608                        "Package already moved to " + volumeUuid);
23609            }
23610            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23611                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23612                        "Device admin cannot be moved");
23613            }
23614
23615            if (mFrozenPackages.contains(packageName)) {
23616                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23617                        "Failed to move already frozen package");
23618            }
23619
23620            codeFile = new File(pkg.codePath);
23621            installerPackageName = ps.installerPackageName;
23622            packageAbiOverride = ps.cpuAbiOverrideString;
23623            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23624            seinfo = pkg.applicationInfo.seInfo;
23625            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23626            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23627            freezer = freezePackage(packageName, "movePackageInternal");
23628            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23629        }
23630
23631        final Bundle extras = new Bundle();
23632        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23633        extras.putString(Intent.EXTRA_TITLE, label);
23634        mMoveCallbacks.notifyCreated(moveId, extras);
23635
23636        int installFlags;
23637        final boolean moveCompleteApp;
23638        final File measurePath;
23639
23640        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23641            installFlags = INSTALL_INTERNAL;
23642            moveCompleteApp = !currentAsec;
23643            measurePath = Environment.getDataAppDirectory(volumeUuid);
23644        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23645            installFlags = INSTALL_EXTERNAL;
23646            moveCompleteApp = false;
23647            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23648        } else {
23649            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23650            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23651                    || !volume.isMountedWritable()) {
23652                freezer.close();
23653                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23654                        "Move location not mounted private volume");
23655            }
23656
23657            Preconditions.checkState(!currentAsec);
23658
23659            installFlags = INSTALL_INTERNAL;
23660            moveCompleteApp = true;
23661            measurePath = Environment.getDataAppDirectory(volumeUuid);
23662        }
23663
23664        final PackageStats stats = new PackageStats(null, -1);
23665        synchronized (mInstaller) {
23666            for (int userId : installedUserIds) {
23667                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23668                    freezer.close();
23669                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23670                            "Failed to measure package size");
23671                }
23672            }
23673        }
23674
23675        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23676                + stats.dataSize);
23677
23678        final long startFreeBytes = measurePath.getUsableSpace();
23679        final long sizeBytes;
23680        if (moveCompleteApp) {
23681            sizeBytes = stats.codeSize + stats.dataSize;
23682        } else {
23683            sizeBytes = stats.codeSize;
23684        }
23685
23686        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23687            freezer.close();
23688            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23689                    "Not enough free space to move");
23690        }
23691
23692        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23693
23694        final CountDownLatch installedLatch = new CountDownLatch(1);
23695        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23696            @Override
23697            public void onUserActionRequired(Intent intent) throws RemoteException {
23698                throw new IllegalStateException();
23699            }
23700
23701            @Override
23702            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23703                    Bundle extras) throws RemoteException {
23704                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23705                        + PackageManager.installStatusToString(returnCode, msg));
23706
23707                installedLatch.countDown();
23708                freezer.close();
23709
23710                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23711                switch (status) {
23712                    case PackageInstaller.STATUS_SUCCESS:
23713                        mMoveCallbacks.notifyStatusChanged(moveId,
23714                                PackageManager.MOVE_SUCCEEDED);
23715                        break;
23716                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23717                        mMoveCallbacks.notifyStatusChanged(moveId,
23718                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23719                        break;
23720                    default:
23721                        mMoveCallbacks.notifyStatusChanged(moveId,
23722                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23723                        break;
23724                }
23725            }
23726        };
23727
23728        final MoveInfo move;
23729        if (moveCompleteApp) {
23730            // Kick off a thread to report progress estimates
23731            new Thread() {
23732                @Override
23733                public void run() {
23734                    while (true) {
23735                        try {
23736                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23737                                break;
23738                            }
23739                        } catch (InterruptedException ignored) {
23740                        }
23741
23742                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23743                        final int progress = 10 + (int) MathUtils.constrain(
23744                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23745                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23746                    }
23747                }
23748            }.start();
23749
23750            final String dataAppName = codeFile.getName();
23751            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23752                    dataAppName, appId, seinfo, targetSdkVersion);
23753        } else {
23754            move = null;
23755        }
23756
23757        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23758
23759        final Message msg = mHandler.obtainMessage(INIT_COPY);
23760        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23761        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23762                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23763                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23764                PackageManager.INSTALL_REASON_UNKNOWN);
23765        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23766        msg.obj = params;
23767
23768        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23769                System.identityHashCode(msg.obj));
23770        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23771                System.identityHashCode(msg.obj));
23772
23773        mHandler.sendMessage(msg);
23774    }
23775
23776    @Override
23777    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23778        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23779
23780        final int realMoveId = mNextMoveId.getAndIncrement();
23781        final Bundle extras = new Bundle();
23782        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23783        mMoveCallbacks.notifyCreated(realMoveId, extras);
23784
23785        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23786            @Override
23787            public void onCreated(int moveId, Bundle extras) {
23788                // Ignored
23789            }
23790
23791            @Override
23792            public void onStatusChanged(int moveId, int status, long estMillis) {
23793                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23794            }
23795        };
23796
23797        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23798        storage.setPrimaryStorageUuid(volumeUuid, callback);
23799        return realMoveId;
23800    }
23801
23802    @Override
23803    public int getMoveStatus(int moveId) {
23804        mContext.enforceCallingOrSelfPermission(
23805                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23806        return mMoveCallbacks.mLastStatus.get(moveId);
23807    }
23808
23809    @Override
23810    public void registerMoveCallback(IPackageMoveObserver callback) {
23811        mContext.enforceCallingOrSelfPermission(
23812                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23813        mMoveCallbacks.register(callback);
23814    }
23815
23816    @Override
23817    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23818        mContext.enforceCallingOrSelfPermission(
23819                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23820        mMoveCallbacks.unregister(callback);
23821    }
23822
23823    @Override
23824    public boolean setInstallLocation(int loc) {
23825        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23826                null);
23827        if (getInstallLocation() == loc) {
23828            return true;
23829        }
23830        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23831                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23832            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23833                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23834            return true;
23835        }
23836        return false;
23837   }
23838
23839    @Override
23840    public int getInstallLocation() {
23841        // allow instant app access
23842        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23843                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23844                PackageHelper.APP_INSTALL_AUTO);
23845    }
23846
23847    /** Called by UserManagerService */
23848    void cleanUpUser(UserManagerService userManager, int userHandle) {
23849        synchronized (mPackages) {
23850            mDirtyUsers.remove(userHandle);
23851            mUserNeedsBadging.delete(userHandle);
23852            mSettings.removeUserLPw(userHandle);
23853            mPendingBroadcasts.remove(userHandle);
23854            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23855            removeUnusedPackagesLPw(userManager, userHandle);
23856        }
23857    }
23858
23859    /**
23860     * We're removing userHandle and would like to remove any downloaded packages
23861     * that are no longer in use by any other user.
23862     * @param userHandle the user being removed
23863     */
23864    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23865        final boolean DEBUG_CLEAN_APKS = false;
23866        int [] users = userManager.getUserIds();
23867        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23868        while (psit.hasNext()) {
23869            PackageSetting ps = psit.next();
23870            if (ps.pkg == null) {
23871                continue;
23872            }
23873            final String packageName = ps.pkg.packageName;
23874            // Skip over if system app
23875            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23876                continue;
23877            }
23878            if (DEBUG_CLEAN_APKS) {
23879                Slog.i(TAG, "Checking package " + packageName);
23880            }
23881            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23882            if (keep) {
23883                if (DEBUG_CLEAN_APKS) {
23884                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23885                }
23886            } else {
23887                for (int i = 0; i < users.length; i++) {
23888                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23889                        keep = true;
23890                        if (DEBUG_CLEAN_APKS) {
23891                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23892                                    + users[i]);
23893                        }
23894                        break;
23895                    }
23896                }
23897            }
23898            if (!keep) {
23899                if (DEBUG_CLEAN_APKS) {
23900                    Slog.i(TAG, "  Removing package " + packageName);
23901                }
23902                mHandler.post(new Runnable() {
23903                    public void run() {
23904                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23905                                userHandle, 0);
23906                    } //end run
23907                });
23908            }
23909        }
23910    }
23911
23912    /** Called by UserManagerService */
23913    void createNewUser(int userId, String[] disallowedPackages) {
23914        synchronized (mInstallLock) {
23915            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23916        }
23917        synchronized (mPackages) {
23918            scheduleWritePackageRestrictionsLocked(userId);
23919            scheduleWritePackageListLocked(userId);
23920            applyFactoryDefaultBrowserLPw(userId);
23921            primeDomainVerificationsLPw(userId);
23922        }
23923    }
23924
23925    void onNewUserCreated(final int userId) {
23926        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23927        // If permission review for legacy apps is required, we represent
23928        // dagerous permissions for such apps as always granted runtime
23929        // permissions to keep per user flag state whether review is needed.
23930        // Hence, if a new user is added we have to propagate dangerous
23931        // permission grants for these legacy apps.
23932        if (mPermissionReviewRequired) {
23933            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23934                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23935        }
23936    }
23937
23938    @Override
23939    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23940        mContext.enforceCallingOrSelfPermission(
23941                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23942                "Only package verification agents can read the verifier device identity");
23943
23944        synchronized (mPackages) {
23945            return mSettings.getVerifierDeviceIdentityLPw();
23946        }
23947    }
23948
23949    @Override
23950    public void setPermissionEnforced(String permission, boolean enforced) {
23951        // TODO: Now that we no longer change GID for storage, this should to away.
23952        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23953                "setPermissionEnforced");
23954        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23955            synchronized (mPackages) {
23956                if (mSettings.mReadExternalStorageEnforced == null
23957                        || mSettings.mReadExternalStorageEnforced != enforced) {
23958                    mSettings.mReadExternalStorageEnforced = enforced;
23959                    mSettings.writeLPr();
23960                }
23961            }
23962            // kill any non-foreground processes so we restart them and
23963            // grant/revoke the GID.
23964            final IActivityManager am = ActivityManager.getService();
23965            if (am != null) {
23966                final long token = Binder.clearCallingIdentity();
23967                try {
23968                    am.killProcessesBelowForeground("setPermissionEnforcement");
23969                } catch (RemoteException e) {
23970                } finally {
23971                    Binder.restoreCallingIdentity(token);
23972                }
23973            }
23974        } else {
23975            throw new IllegalArgumentException("No selective enforcement for " + permission);
23976        }
23977    }
23978
23979    @Override
23980    @Deprecated
23981    public boolean isPermissionEnforced(String permission) {
23982        // allow instant applications
23983        return true;
23984    }
23985
23986    @Override
23987    public boolean isStorageLow() {
23988        // allow instant applications
23989        final long token = Binder.clearCallingIdentity();
23990        try {
23991            final DeviceStorageMonitorInternal
23992                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23993            if (dsm != null) {
23994                return dsm.isMemoryLow();
23995            } else {
23996                return false;
23997            }
23998        } finally {
23999            Binder.restoreCallingIdentity(token);
24000        }
24001    }
24002
24003    @Override
24004    public IPackageInstaller getPackageInstaller() {
24005        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24006            return null;
24007        }
24008        return mInstallerService;
24009    }
24010
24011    private boolean userNeedsBadging(int userId) {
24012        int index = mUserNeedsBadging.indexOfKey(userId);
24013        if (index < 0) {
24014            final UserInfo userInfo;
24015            final long token = Binder.clearCallingIdentity();
24016            try {
24017                userInfo = sUserManager.getUserInfo(userId);
24018            } finally {
24019                Binder.restoreCallingIdentity(token);
24020            }
24021            final boolean b;
24022            if (userInfo != null && userInfo.isManagedProfile()) {
24023                b = true;
24024            } else {
24025                b = false;
24026            }
24027            mUserNeedsBadging.put(userId, b);
24028            return b;
24029        }
24030        return mUserNeedsBadging.valueAt(index);
24031    }
24032
24033    @Override
24034    public KeySet getKeySetByAlias(String packageName, String alias) {
24035        if (packageName == null || alias == null) {
24036            return null;
24037        }
24038        synchronized(mPackages) {
24039            final PackageParser.Package pkg = mPackages.get(packageName);
24040            if (pkg == null) {
24041                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24042                throw new IllegalArgumentException("Unknown package: " + packageName);
24043            }
24044            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24045            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24046                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24047                throw new IllegalArgumentException("Unknown package: " + packageName);
24048            }
24049            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24050            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24051        }
24052    }
24053
24054    @Override
24055    public KeySet getSigningKeySet(String packageName) {
24056        if (packageName == null) {
24057            return null;
24058        }
24059        synchronized(mPackages) {
24060            final int callingUid = Binder.getCallingUid();
24061            final int callingUserId = UserHandle.getUserId(callingUid);
24062            final PackageParser.Package pkg = mPackages.get(packageName);
24063            if (pkg == null) {
24064                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24065                throw new IllegalArgumentException("Unknown package: " + packageName);
24066            }
24067            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24068            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24069                // filter and pretend the package doesn't exist
24070                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24071                        + ", uid:" + callingUid);
24072                throw new IllegalArgumentException("Unknown package: " + packageName);
24073            }
24074            if (pkg.applicationInfo.uid != callingUid
24075                    && Process.SYSTEM_UID != callingUid) {
24076                throw new SecurityException("May not access signing KeySet of other apps.");
24077            }
24078            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24079            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24080        }
24081    }
24082
24083    @Override
24084    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24085        final int callingUid = Binder.getCallingUid();
24086        if (getInstantAppPackageName(callingUid) != null) {
24087            return false;
24088        }
24089        if (packageName == null || ks == null) {
24090            return false;
24091        }
24092        synchronized(mPackages) {
24093            final PackageParser.Package pkg = mPackages.get(packageName);
24094            if (pkg == null
24095                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24096                            UserHandle.getUserId(callingUid))) {
24097                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24098                throw new IllegalArgumentException("Unknown package: " + packageName);
24099            }
24100            IBinder ksh = ks.getToken();
24101            if (ksh instanceof KeySetHandle) {
24102                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24103                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24104            }
24105            return false;
24106        }
24107    }
24108
24109    @Override
24110    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24111        final int callingUid = Binder.getCallingUid();
24112        if (getInstantAppPackageName(callingUid) != null) {
24113            return false;
24114        }
24115        if (packageName == null || ks == null) {
24116            return false;
24117        }
24118        synchronized(mPackages) {
24119            final PackageParser.Package pkg = mPackages.get(packageName);
24120            if (pkg == null
24121                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24122                            UserHandle.getUserId(callingUid))) {
24123                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24124                throw new IllegalArgumentException("Unknown package: " + packageName);
24125            }
24126            IBinder ksh = ks.getToken();
24127            if (ksh instanceof KeySetHandle) {
24128                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24129                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24130            }
24131            return false;
24132        }
24133    }
24134
24135    private void deletePackageIfUnusedLPr(final String packageName) {
24136        PackageSetting ps = mSettings.mPackages.get(packageName);
24137        if (ps == null) {
24138            return;
24139        }
24140        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24141            // TODO Implement atomic delete if package is unused
24142            // It is currently possible that the package will be deleted even if it is installed
24143            // after this method returns.
24144            mHandler.post(new Runnable() {
24145                public void run() {
24146                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24147                            0, PackageManager.DELETE_ALL_USERS);
24148                }
24149            });
24150        }
24151    }
24152
24153    /**
24154     * Check and throw if the given before/after packages would be considered a
24155     * downgrade.
24156     */
24157    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24158            throws PackageManagerException {
24159        if (after.versionCode < before.mVersionCode) {
24160            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24161                    "Update version code " + after.versionCode + " is older than current "
24162                    + before.mVersionCode);
24163        } else if (after.versionCode == before.mVersionCode) {
24164            if (after.baseRevisionCode < before.baseRevisionCode) {
24165                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24166                        "Update base revision code " + after.baseRevisionCode
24167                        + " is older than current " + before.baseRevisionCode);
24168            }
24169
24170            if (!ArrayUtils.isEmpty(after.splitNames)) {
24171                for (int i = 0; i < after.splitNames.length; i++) {
24172                    final String splitName = after.splitNames[i];
24173                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24174                    if (j != -1) {
24175                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24176                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24177                                    "Update split " + splitName + " revision code "
24178                                    + after.splitRevisionCodes[i] + " is older than current "
24179                                    + before.splitRevisionCodes[j]);
24180                        }
24181                    }
24182                }
24183            }
24184        }
24185    }
24186
24187    private static class MoveCallbacks extends Handler {
24188        private static final int MSG_CREATED = 1;
24189        private static final int MSG_STATUS_CHANGED = 2;
24190
24191        private final RemoteCallbackList<IPackageMoveObserver>
24192                mCallbacks = new RemoteCallbackList<>();
24193
24194        private final SparseIntArray mLastStatus = new SparseIntArray();
24195
24196        public MoveCallbacks(Looper looper) {
24197            super(looper);
24198        }
24199
24200        public void register(IPackageMoveObserver callback) {
24201            mCallbacks.register(callback);
24202        }
24203
24204        public void unregister(IPackageMoveObserver callback) {
24205            mCallbacks.unregister(callback);
24206        }
24207
24208        @Override
24209        public void handleMessage(Message msg) {
24210            final SomeArgs args = (SomeArgs) msg.obj;
24211            final int n = mCallbacks.beginBroadcast();
24212            for (int i = 0; i < n; i++) {
24213                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24214                try {
24215                    invokeCallback(callback, msg.what, args);
24216                } catch (RemoteException ignored) {
24217                }
24218            }
24219            mCallbacks.finishBroadcast();
24220            args.recycle();
24221        }
24222
24223        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24224                throws RemoteException {
24225            switch (what) {
24226                case MSG_CREATED: {
24227                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24228                    break;
24229                }
24230                case MSG_STATUS_CHANGED: {
24231                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24232                    break;
24233                }
24234            }
24235        }
24236
24237        private void notifyCreated(int moveId, Bundle extras) {
24238            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24239
24240            final SomeArgs args = SomeArgs.obtain();
24241            args.argi1 = moveId;
24242            args.arg2 = extras;
24243            obtainMessage(MSG_CREATED, args).sendToTarget();
24244        }
24245
24246        private void notifyStatusChanged(int moveId, int status) {
24247            notifyStatusChanged(moveId, status, -1);
24248        }
24249
24250        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24251            Slog.v(TAG, "Move " + moveId + " status " + status);
24252
24253            final SomeArgs args = SomeArgs.obtain();
24254            args.argi1 = moveId;
24255            args.argi2 = status;
24256            args.arg3 = estMillis;
24257            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24258
24259            synchronized (mLastStatus) {
24260                mLastStatus.put(moveId, status);
24261            }
24262        }
24263    }
24264
24265    private final static class OnPermissionChangeListeners extends Handler {
24266        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24267
24268        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24269                new RemoteCallbackList<>();
24270
24271        public OnPermissionChangeListeners(Looper looper) {
24272            super(looper);
24273        }
24274
24275        @Override
24276        public void handleMessage(Message msg) {
24277            switch (msg.what) {
24278                case MSG_ON_PERMISSIONS_CHANGED: {
24279                    final int uid = msg.arg1;
24280                    handleOnPermissionsChanged(uid);
24281                } break;
24282            }
24283        }
24284
24285        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24286            mPermissionListeners.register(listener);
24287
24288        }
24289
24290        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24291            mPermissionListeners.unregister(listener);
24292        }
24293
24294        public void onPermissionsChanged(int uid) {
24295            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24296                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24297            }
24298        }
24299
24300        private void handleOnPermissionsChanged(int uid) {
24301            final int count = mPermissionListeners.beginBroadcast();
24302            try {
24303                for (int i = 0; i < count; i++) {
24304                    IOnPermissionsChangeListener callback = mPermissionListeners
24305                            .getBroadcastItem(i);
24306                    try {
24307                        callback.onPermissionsChanged(uid);
24308                    } catch (RemoteException e) {
24309                        Log.e(TAG, "Permission listener is dead", e);
24310                    }
24311                }
24312            } finally {
24313                mPermissionListeners.finishBroadcast();
24314            }
24315        }
24316    }
24317
24318    private class PackageManagerInternalImpl extends PackageManagerInternal {
24319        @Override
24320        public void setLocationPackagesProvider(PackagesProvider provider) {
24321            synchronized (mPackages) {
24322                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24323            }
24324        }
24325
24326        @Override
24327        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24328            synchronized (mPackages) {
24329                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24330            }
24331        }
24332
24333        @Override
24334        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24335            synchronized (mPackages) {
24336                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24337            }
24338        }
24339
24340        @Override
24341        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24342            synchronized (mPackages) {
24343                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24344            }
24345        }
24346
24347        @Override
24348        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24349            synchronized (mPackages) {
24350                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24351            }
24352        }
24353
24354        @Override
24355        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24356            synchronized (mPackages) {
24357                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24358            }
24359        }
24360
24361        @Override
24362        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24363            synchronized (mPackages) {
24364                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24365                        packageName, userId);
24366            }
24367        }
24368
24369        @Override
24370        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24371            synchronized (mPackages) {
24372                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24373                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24374                        packageName, userId);
24375            }
24376        }
24377
24378        @Override
24379        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24380            synchronized (mPackages) {
24381                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24382                        packageName, userId);
24383            }
24384        }
24385
24386        @Override
24387        public void setKeepUninstalledPackages(final List<String> packageList) {
24388            Preconditions.checkNotNull(packageList);
24389            List<String> removedFromList = null;
24390            synchronized (mPackages) {
24391                if (mKeepUninstalledPackages != null) {
24392                    final int packagesCount = mKeepUninstalledPackages.size();
24393                    for (int i = 0; i < packagesCount; i++) {
24394                        String oldPackage = mKeepUninstalledPackages.get(i);
24395                        if (packageList != null && packageList.contains(oldPackage)) {
24396                            continue;
24397                        }
24398                        if (removedFromList == null) {
24399                            removedFromList = new ArrayList<>();
24400                        }
24401                        removedFromList.add(oldPackage);
24402                    }
24403                }
24404                mKeepUninstalledPackages = new ArrayList<>(packageList);
24405                if (removedFromList != null) {
24406                    final int removedCount = removedFromList.size();
24407                    for (int i = 0; i < removedCount; i++) {
24408                        deletePackageIfUnusedLPr(removedFromList.get(i));
24409                    }
24410                }
24411            }
24412        }
24413
24414        @Override
24415        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24416            synchronized (mPackages) {
24417                // If we do not support permission review, done.
24418                if (!mPermissionReviewRequired) {
24419                    return false;
24420                }
24421
24422                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24423                if (packageSetting == null) {
24424                    return false;
24425                }
24426
24427                // Permission review applies only to apps not supporting the new permission model.
24428                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24429                    return false;
24430                }
24431
24432                // Legacy apps have the permission and get user consent on launch.
24433                PermissionsState permissionsState = packageSetting.getPermissionsState();
24434                return permissionsState.isPermissionReviewRequired(userId);
24435            }
24436        }
24437
24438        @Override
24439        public PackageInfo getPackageInfo(
24440                String packageName, int flags, int filterCallingUid, int userId) {
24441            return PackageManagerService.this
24442                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24443                            flags, filterCallingUid, userId);
24444        }
24445
24446        @Override
24447        public ApplicationInfo getApplicationInfo(
24448                String packageName, int flags, int filterCallingUid, int userId) {
24449            return PackageManagerService.this
24450                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24451        }
24452
24453        @Override
24454        public ActivityInfo getActivityInfo(
24455                ComponentName component, int flags, int filterCallingUid, int userId) {
24456            return PackageManagerService.this
24457                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24458        }
24459
24460        @Override
24461        public List<ResolveInfo> queryIntentActivities(
24462                Intent intent, int flags, int filterCallingUid, int userId) {
24463            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24464            return PackageManagerService.this
24465                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24466                            userId, false /*resolveForStart*/);
24467        }
24468
24469        @Override
24470        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24471                int userId) {
24472            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24473        }
24474
24475        @Override
24476        public void setDeviceAndProfileOwnerPackages(
24477                int deviceOwnerUserId, String deviceOwnerPackage,
24478                SparseArray<String> profileOwnerPackages) {
24479            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24480                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24481        }
24482
24483        @Override
24484        public boolean isPackageDataProtected(int userId, String packageName) {
24485            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24486        }
24487
24488        @Override
24489        public boolean isPackageEphemeral(int userId, String packageName) {
24490            synchronized (mPackages) {
24491                final PackageSetting ps = mSettings.mPackages.get(packageName);
24492                return ps != null ? ps.getInstantApp(userId) : false;
24493            }
24494        }
24495
24496        @Override
24497        public boolean wasPackageEverLaunched(String packageName, int userId) {
24498            synchronized (mPackages) {
24499                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24500            }
24501        }
24502
24503        @Override
24504        public void grantRuntimePermission(String packageName, String name, int userId,
24505                boolean overridePolicy) {
24506            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24507                    overridePolicy);
24508        }
24509
24510        @Override
24511        public void revokeRuntimePermission(String packageName, String name, int userId,
24512                boolean overridePolicy) {
24513            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24514                    overridePolicy);
24515        }
24516
24517        @Override
24518        public String getNameForUid(int uid) {
24519            return PackageManagerService.this.getNameForUid(uid);
24520        }
24521
24522        @Override
24523        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24524                Intent origIntent, String resolvedType, String callingPackage,
24525                Bundle verificationBundle, int userId) {
24526            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24527                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24528                    userId);
24529        }
24530
24531        @Override
24532        public void grantEphemeralAccess(int userId, Intent intent,
24533                int targetAppId, int ephemeralAppId) {
24534            synchronized (mPackages) {
24535                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24536                        targetAppId, ephemeralAppId);
24537            }
24538        }
24539
24540        @Override
24541        public boolean isInstantAppInstallerComponent(ComponentName component) {
24542            synchronized (mPackages) {
24543                return mInstantAppInstallerActivity != null
24544                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24545            }
24546        }
24547
24548        @Override
24549        public void pruneInstantApps() {
24550            mInstantAppRegistry.pruneInstantApps();
24551        }
24552
24553        @Override
24554        public String getSetupWizardPackageName() {
24555            return mSetupWizardPackage;
24556        }
24557
24558        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24559            if (policy != null) {
24560                mExternalSourcesPolicy = policy;
24561            }
24562        }
24563
24564        @Override
24565        public boolean isPackagePersistent(String packageName) {
24566            synchronized (mPackages) {
24567                PackageParser.Package pkg = mPackages.get(packageName);
24568                return pkg != null
24569                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24570                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24571                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24572                        : false;
24573            }
24574        }
24575
24576        @Override
24577        public List<PackageInfo> getOverlayPackages(int userId) {
24578            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24579            synchronized (mPackages) {
24580                for (PackageParser.Package p : mPackages.values()) {
24581                    if (p.mOverlayTarget != null) {
24582                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24583                        if (pkg != null) {
24584                            overlayPackages.add(pkg);
24585                        }
24586                    }
24587                }
24588            }
24589            return overlayPackages;
24590        }
24591
24592        @Override
24593        public List<String> getTargetPackageNames(int userId) {
24594            List<String> targetPackages = new ArrayList<>();
24595            synchronized (mPackages) {
24596                for (PackageParser.Package p : mPackages.values()) {
24597                    if (p.mOverlayTarget == null) {
24598                        targetPackages.add(p.packageName);
24599                    }
24600                }
24601            }
24602            return targetPackages;
24603        }
24604
24605        @Override
24606        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24607                @Nullable List<String> overlayPackageNames) {
24608            synchronized (mPackages) {
24609                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24610                    Slog.e(TAG, "failed to find package " + targetPackageName);
24611                    return false;
24612                }
24613                ArrayList<String> overlayPaths = null;
24614                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24615                    final int N = overlayPackageNames.size();
24616                    overlayPaths = new ArrayList<>(N);
24617                    for (int i = 0; i < N; i++) {
24618                        final String packageName = overlayPackageNames.get(i);
24619                        final PackageParser.Package pkg = mPackages.get(packageName);
24620                        if (pkg == null) {
24621                            Slog.e(TAG, "failed to find package " + packageName);
24622                            return false;
24623                        }
24624                        overlayPaths.add(pkg.baseCodePath);
24625                    }
24626                }
24627
24628                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24629                ps.setOverlayPaths(overlayPaths, userId);
24630                return true;
24631            }
24632        }
24633
24634        @Override
24635        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24636                int flags, int userId) {
24637            return resolveIntentInternal(
24638                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24639        }
24640
24641        @Override
24642        public ResolveInfo resolveService(Intent intent, String resolvedType,
24643                int flags, int userId, int callingUid) {
24644            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24645        }
24646
24647        @Override
24648        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24649            synchronized (mPackages) {
24650                mIsolatedOwners.put(isolatedUid, ownerUid);
24651            }
24652        }
24653
24654        @Override
24655        public void removeIsolatedUid(int isolatedUid) {
24656            synchronized (mPackages) {
24657                mIsolatedOwners.delete(isolatedUid);
24658            }
24659        }
24660
24661        @Override
24662        public int getUidTargetSdkVersion(int uid) {
24663            synchronized (mPackages) {
24664                return getUidTargetSdkVersionLockedLPr(uid);
24665            }
24666        }
24667
24668        @Override
24669        public boolean canAccessInstantApps(int callingUid, int userId) {
24670            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24671        }
24672    }
24673
24674    @Override
24675    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24676        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24677        synchronized (mPackages) {
24678            final long identity = Binder.clearCallingIdentity();
24679            try {
24680                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24681                        packageNames, userId);
24682            } finally {
24683                Binder.restoreCallingIdentity(identity);
24684            }
24685        }
24686    }
24687
24688    @Override
24689    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24690        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24691        synchronized (mPackages) {
24692            final long identity = Binder.clearCallingIdentity();
24693            try {
24694                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24695                        packageNames, userId);
24696            } finally {
24697                Binder.restoreCallingIdentity(identity);
24698            }
24699        }
24700    }
24701
24702    private static void enforceSystemOrPhoneCaller(String tag) {
24703        int callingUid = Binder.getCallingUid();
24704        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24705            throw new SecurityException(
24706                    "Cannot call " + tag + " from UID " + callingUid);
24707        }
24708    }
24709
24710    boolean isHistoricalPackageUsageAvailable() {
24711        return mPackageUsage.isHistoricalPackageUsageAvailable();
24712    }
24713
24714    /**
24715     * Return a <b>copy</b> of the collection of packages known to the package manager.
24716     * @return A copy of the values of mPackages.
24717     */
24718    Collection<PackageParser.Package> getPackages() {
24719        synchronized (mPackages) {
24720            return new ArrayList<>(mPackages.values());
24721        }
24722    }
24723
24724    /**
24725     * Logs process start information (including base APK hash) to the security log.
24726     * @hide
24727     */
24728    @Override
24729    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24730            String apkFile, int pid) {
24731        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24732            return;
24733        }
24734        if (!SecurityLog.isLoggingEnabled()) {
24735            return;
24736        }
24737        Bundle data = new Bundle();
24738        data.putLong("startTimestamp", System.currentTimeMillis());
24739        data.putString("processName", processName);
24740        data.putInt("uid", uid);
24741        data.putString("seinfo", seinfo);
24742        data.putString("apkFile", apkFile);
24743        data.putInt("pid", pid);
24744        Message msg = mProcessLoggingHandler.obtainMessage(
24745                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24746        msg.setData(data);
24747        mProcessLoggingHandler.sendMessage(msg);
24748    }
24749
24750    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24751        return mCompilerStats.getPackageStats(pkgName);
24752    }
24753
24754    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24755        return getOrCreateCompilerPackageStats(pkg.packageName);
24756    }
24757
24758    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24759        return mCompilerStats.getOrCreatePackageStats(pkgName);
24760    }
24761
24762    public void deleteCompilerPackageStats(String pkgName) {
24763        mCompilerStats.deletePackageStats(pkgName);
24764    }
24765
24766    @Override
24767    public int getInstallReason(String packageName, int userId) {
24768        final int callingUid = Binder.getCallingUid();
24769        enforceCrossUserPermission(callingUid, userId,
24770                true /* requireFullPermission */, false /* checkShell */,
24771                "get install reason");
24772        synchronized (mPackages) {
24773            final PackageSetting ps = mSettings.mPackages.get(packageName);
24774            if (filterAppAccessLPr(ps, callingUid, userId)) {
24775                return PackageManager.INSTALL_REASON_UNKNOWN;
24776            }
24777            if (ps != null) {
24778                return ps.getInstallReason(userId);
24779            }
24780        }
24781        return PackageManager.INSTALL_REASON_UNKNOWN;
24782    }
24783
24784    @Override
24785    public boolean canRequestPackageInstalls(String packageName, int userId) {
24786        return canRequestPackageInstallsInternal(packageName, 0, userId,
24787                true /* throwIfPermNotDeclared*/);
24788    }
24789
24790    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24791            boolean throwIfPermNotDeclared) {
24792        int callingUid = Binder.getCallingUid();
24793        int uid = getPackageUid(packageName, 0, userId);
24794        if (callingUid != uid && callingUid != Process.ROOT_UID
24795                && callingUid != Process.SYSTEM_UID) {
24796            throw new SecurityException(
24797                    "Caller uid " + callingUid + " does not own package " + packageName);
24798        }
24799        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24800        if (info == null) {
24801            return false;
24802        }
24803        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24804            return false;
24805        }
24806        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24807        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24808        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24809            if (throwIfPermNotDeclared) {
24810                throw new SecurityException("Need to declare " + appOpPermission
24811                        + " to call this api");
24812            } else {
24813                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24814                return false;
24815            }
24816        }
24817        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24818            return false;
24819        }
24820        if (mExternalSourcesPolicy != null) {
24821            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24822            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24823                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24824            }
24825        }
24826        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24827    }
24828
24829    @Override
24830    public ComponentName getInstantAppResolverSettingsComponent() {
24831        return mInstantAppResolverSettingsComponent;
24832    }
24833
24834    @Override
24835    public ComponentName getInstantAppInstallerComponent() {
24836        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24837            return null;
24838        }
24839        return mInstantAppInstallerActivity == null
24840                ? null : mInstantAppInstallerActivity.getComponentName();
24841    }
24842
24843    @Override
24844    public String getInstantAppAndroidId(String packageName, int userId) {
24845        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24846                "getInstantAppAndroidId");
24847        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24848                true /* requireFullPermission */, false /* checkShell */,
24849                "getInstantAppAndroidId");
24850        // Make sure the target is an Instant App.
24851        if (!isInstantApp(packageName, userId)) {
24852            return null;
24853        }
24854        synchronized (mPackages) {
24855            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24856        }
24857    }
24858}
24859
24860interface PackageSender {
24861    void sendPackageBroadcast(final String action, final String pkg,
24862        final Bundle extras, final int flags, final String targetPkg,
24863        final IIntentReceiver finishedReceiver, final int[] userIds);
24864    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24865        int appId, int... userIds);
24866}
24867