PackageManagerService.java revision 13dcd27fb54546d33fa949ec9e7b81fc973ecb88
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
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.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.DumpUtils;
258import com.android.internal.util.FastPrintWriter;
259import com.android.internal.util.FastXmlSerializer;
260import com.android.internal.util.IndentingPrintWriter;
261import com.android.internal.util.Preconditions;
262import com.android.internal.util.XmlUtils;
263import com.android.server.AttributeCache;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.LockGuard;
270import com.android.server.ServiceThread;
271import com.android.server.SystemConfig;
272import com.android.server.SystemServerInitThreadPool;
273import com.android.server.Watchdog;
274import com.android.server.net.NetworkPolicyManagerInternal;
275import com.android.server.pm.BackgroundDexOptService;
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.FileNotFoundException;
302import java.io.FileOutputStream;
303import java.io.FileReader;
304import java.io.FilenameFilter;
305import java.io.IOException;
306import java.io.PrintWriter;
307import java.nio.charset.StandardCharsets;
308import java.security.DigestInputStream;
309import java.security.MessageDigest;
310import java.security.NoSuchAlgorithmException;
311import java.security.PublicKey;
312import java.security.SecureRandom;
313import java.security.cert.Certificate;
314import java.security.cert.CertificateEncodingException;
315import java.security.cert.CertificateException;
316import java.text.SimpleDateFormat;
317import java.util.ArrayList;
318import java.util.Arrays;
319import java.util.Collection;
320import java.util.Collections;
321import java.util.Comparator;
322import java.util.Date;
323import java.util.HashMap;
324import java.util.HashSet;
325import java.util.Iterator;
326import java.util.List;
327import java.util.Map;
328import java.util.Objects;
329import java.util.Set;
330import java.util.concurrent.CountDownLatch;
331import java.util.concurrent.Future;
332import java.util.concurrent.TimeUnit;
333import java.util.concurrent.atomic.AtomicBoolean;
334import java.util.concurrent.atomic.AtomicInteger;
335
336/**
337 * Keep track of all those APKs everywhere.
338 * <p>
339 * Internally there are two important locks:
340 * <ul>
341 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
342 * and other related state. It is a fine-grained lock that should only be held
343 * momentarily, as it's one of the most contended locks in the system.
344 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
345 * operations typically involve heavy lifting of application data on disk. Since
346 * {@code installd} is single-threaded, and it's operations can often be slow,
347 * this lock should never be acquired while already holding {@link #mPackages}.
348 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
349 * holding {@link #mInstallLock}.
350 * </ul>
351 * Many internal methods rely on the caller to hold the appropriate locks, and
352 * this contract is expressed through method name suffixes:
353 * <ul>
354 * <li>fooLI(): the caller must hold {@link #mInstallLock}
355 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
356 * being modified must be frozen
357 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
358 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
359 * </ul>
360 * <p>
361 * Because this class is very central to the platform's security; please run all
362 * CTS and unit tests whenever making modifications:
363 *
364 * <pre>
365 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
366 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
367 * </pre>
368 */
369public class PackageManagerService extends IPackageManager.Stub {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385
386    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
387    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
388    // user, but by default initialize to this.
389    public static final boolean DEBUG_DEXOPT = false;
390
391    private static final boolean DEBUG_ABI_SELECTION = false;
392    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
393    private static final boolean DEBUG_TRIAGED_MISSING = false;
394    private static final boolean DEBUG_APP_DATA = false;
395
396    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
397    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
398
399    private static final boolean DISABLE_EPHEMERAL_APPS = false;
400    private static final boolean HIDE_EPHEMERAL_APIS = false;
401
402    private static final boolean ENABLE_FREE_CACHE_V2 =
403            SystemProperties.getBoolean("fw.free_cache_v2", true);
404
405    private static final int RADIO_UID = Process.PHONE_UID;
406    private static final int LOG_UID = Process.LOG_UID;
407    private static final int NFC_UID = Process.NFC_UID;
408    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
409    private static final int SHELL_UID = Process.SHELL_UID;
410
411    // Cap the size of permission trees that 3rd party apps can define
412    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
413
414    // Suffix used during package installation when copying/moving
415    // package apks to install directory.
416    private static final String INSTALL_PACKAGE_SUFFIX = "-";
417
418    static final int SCAN_NO_DEX = 1<<1;
419    static final int SCAN_FORCE_DEX = 1<<2;
420    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
421    static final int SCAN_NEW_INSTALL = 1<<4;
422    static final int SCAN_UPDATE_TIME = 1<<5;
423    static final int SCAN_BOOTING = 1<<6;
424    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
425    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
426    static final int SCAN_REPLACING = 1<<9;
427    static final int SCAN_REQUIRE_KNOWN = 1<<10;
428    static final int SCAN_MOVE = 1<<11;
429    static final int SCAN_INITIAL = 1<<12;
430    static final int SCAN_CHECK_ONLY = 1<<13;
431    static final int SCAN_DONT_KILL_APP = 1<<14;
432    static final int SCAN_IGNORE_FROZEN = 1<<15;
433    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
434    static final int SCAN_AS_INSTANT_APP = 1<<17;
435    static final int SCAN_AS_FULL_APP = 1<<18;
436    /** Should not be with the scan flags */
437    static final int FLAGS_REMOVE_CHATTY = 1<<31;
438
439    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
440
441    private static final int[] EMPTY_INT_ARRAY = new int[0];
442
443    /**
444     * Timeout (in milliseconds) after which the watchdog should declare that
445     * our handler thread is wedged.  The usual default for such things is one
446     * minute but we sometimes do very lengthy I/O operations on this thread,
447     * such as installing multi-gigabyte applications, so ours needs to be longer.
448     */
449    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
450
451    /**
452     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
453     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
454     * settings entry if available, otherwise we use the hardcoded default.  If it's been
455     * more than this long since the last fstrim, we force one during the boot sequence.
456     *
457     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
458     * one gets run at the next available charging+idle time.  This final mandatory
459     * no-fstrim check kicks in only of the other scheduling criteria is never met.
460     */
461    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
462
463    /**
464     * Whether verification is enabled by default.
465     */
466    private static final boolean DEFAULT_VERIFY_ENABLE = true;
467
468    /**
469     * The default maximum time to wait for the verification agent to return in
470     * milliseconds.
471     */
472    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
473
474    /**
475     * The default response for package verification timeout.
476     *
477     * This can be either PackageManager.VERIFICATION_ALLOW or
478     * PackageManager.VERIFICATION_REJECT.
479     */
480    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
481
482    static final String PLATFORM_PACKAGE_NAME = "android";
483
484    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
485
486    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
487            DEFAULT_CONTAINER_PACKAGE,
488            "com.android.defcontainer.DefaultContainerService");
489
490    private static final String KILL_APP_REASON_GIDS_CHANGED =
491            "permission grant or revoke changed gids";
492
493    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
494            "permissions revoked";
495
496    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
497
498    private static final String PACKAGE_SCHEME = "package";
499
500    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
501
502    /** Permission grant: not grant the permission. */
503    private static final int GRANT_DENIED = 1;
504
505    /** Permission grant: grant the permission as an install permission. */
506    private static final int GRANT_INSTALL = 2;
507
508    /** Permission grant: grant the permission as a runtime one. */
509    private static final int GRANT_RUNTIME = 3;
510
511    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
512    private static final int GRANT_UPGRADE = 4;
513
514    /** Canonical intent used to identify what counts as a "web browser" app */
515    private static final Intent sBrowserIntent;
516    static {
517        sBrowserIntent = new Intent();
518        sBrowserIntent.setAction(Intent.ACTION_VIEW);
519        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
520        sBrowserIntent.setData(Uri.parse("http:"));
521    }
522
523    /**
524     * The set of all protected actions [i.e. those actions for which a high priority
525     * intent filter is disallowed].
526     */
527    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
528    static {
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
531        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
532        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
533    }
534
535    // Compilation reasons.
536    public static final int REASON_FIRST_BOOT = 0;
537    public static final int REASON_BOOT = 1;
538    public static final int REASON_INSTALL = 2;
539    public static final int REASON_BACKGROUND_DEXOPT = 3;
540    public static final int REASON_AB_OTA = 4;
541    public static final int REASON_FORCED_DEXOPT = 5;
542
543    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
544
545    /** All dangerous permission names in the same order as the events in MetricsEvent */
546    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
547            Manifest.permission.READ_CALENDAR,
548            Manifest.permission.WRITE_CALENDAR,
549            Manifest.permission.CAMERA,
550            Manifest.permission.READ_CONTACTS,
551            Manifest.permission.WRITE_CONTACTS,
552            Manifest.permission.GET_ACCOUNTS,
553            Manifest.permission.ACCESS_FINE_LOCATION,
554            Manifest.permission.ACCESS_COARSE_LOCATION,
555            Manifest.permission.RECORD_AUDIO,
556            Manifest.permission.READ_PHONE_STATE,
557            Manifest.permission.CALL_PHONE,
558            Manifest.permission.READ_CALL_LOG,
559            Manifest.permission.WRITE_CALL_LOG,
560            Manifest.permission.ADD_VOICEMAIL,
561            Manifest.permission.USE_SIP,
562            Manifest.permission.PROCESS_OUTGOING_CALLS,
563            Manifest.permission.READ_CELL_BROADCASTS,
564            Manifest.permission.BODY_SENSORS,
565            Manifest.permission.SEND_SMS,
566            Manifest.permission.RECEIVE_SMS,
567            Manifest.permission.READ_SMS,
568            Manifest.permission.RECEIVE_WAP_PUSH,
569            Manifest.permission.RECEIVE_MMS,
570            Manifest.permission.READ_EXTERNAL_STORAGE,
571            Manifest.permission.WRITE_EXTERNAL_STORAGE,
572            Manifest.permission.READ_PHONE_NUMBERS,
573            Manifest.permission.ANSWER_PHONE_CALLS);
574
575
576    /**
577     * Version number for the package parser cache. Increment this whenever the format or
578     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
579     */
580    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
581
582    /**
583     * Whether the package parser cache is enabled.
584     */
585    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
586
587    final ServiceThread mHandlerThread;
588
589    final PackageHandler mHandler;
590
591    private final ProcessLoggingHandler mProcessLoggingHandler;
592
593    /**
594     * Messages for {@link #mHandler} that need to wait for system ready before
595     * being dispatched.
596     */
597    private ArrayList<Message> mPostSystemReadyMessages;
598
599    final int mSdkVersion = Build.VERSION.SDK_INT;
600
601    final Context mContext;
602    final boolean mFactoryTest;
603    final boolean mOnlyCore;
604    final DisplayMetrics mMetrics;
605    final int mDefParseFlags;
606    final String[] mSeparateProcesses;
607    final boolean mIsUpgrade;
608    final boolean mIsPreNUpgrade;
609    final boolean mIsPreNMR1Upgrade;
610
611    // Have we told the Activity Manager to whitelist the default container service by uid yet?
612    @GuardedBy("mPackages")
613    boolean mDefaultContainerWhitelisted = false;
614
615    @GuardedBy("mPackages")
616    private boolean mDexOptDialogShown;
617
618    /** The location for ASEC container files on internal storage. */
619    final String mAsecInternalPath;
620
621    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
622    // LOCK HELD.  Can be called with mInstallLock held.
623    @GuardedBy("mInstallLock")
624    final Installer mInstaller;
625
626    /** Directory where installed third-party apps stored */
627    final File mAppInstallDir;
628
629    /**
630     * Directory to which applications installed internally have their
631     * 32 bit native libraries copied.
632     */
633    private File mAppLib32InstallDir;
634
635    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
636    // apps.
637    final File mDrmAppPrivateInstallDir;
638
639    // ----------------------------------------------------------------
640
641    // Lock for state used when installing and doing other long running
642    // operations.  Methods that must be called with this lock held have
643    // the suffix "LI".
644    final Object mInstallLock = new Object();
645
646    // ----------------------------------------------------------------
647
648    // Keys are String (package name), values are Package.  This also serves
649    // as the lock for the global state.  Methods that must be called with
650    // this lock held have the prefix "LP".
651    @GuardedBy("mPackages")
652    final ArrayMap<String, PackageParser.Package> mPackages =
653            new ArrayMap<String, PackageParser.Package>();
654
655    final ArrayMap<String, Set<String>> mKnownCodebase =
656            new ArrayMap<String, Set<String>>();
657
658    // Keys are isolated uids and values are the uid of the application
659    // that created the isolated proccess.
660    @GuardedBy("mPackages")
661    final SparseIntArray mIsolatedOwners = new SparseIntArray();
662
663    // List of APK paths to load for each user and package. This data is never
664    // persisted by the package manager. Instead, the overlay manager will
665    // ensure the data is up-to-date in runtime.
666    @GuardedBy("mPackages")
667    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
668        new SparseArray<ArrayMap<String, ArrayList<String>>>();
669
670    /**
671     * Tracks new system packages [received in an OTA] that we expect to
672     * find updated user-installed versions. Keys are package name, values
673     * are package location.
674     */
675    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
676    /**
677     * Tracks high priority intent filters for protected actions. During boot, certain
678     * filter actions are protected and should never be allowed to have a high priority
679     * intent filter for them. However, there is one, and only one exception -- the
680     * setup wizard. It must be able to define a high priority intent filter for these
681     * actions to ensure there are no escapes from the wizard. We need to delay processing
682     * of these during boot as we need to look at all of the system packages in order
683     * to know which component is the setup wizard.
684     */
685    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
686    /**
687     * Whether or not processing protected filters should be deferred.
688     */
689    private boolean mDeferProtectedFilters = true;
690
691    /**
692     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
693     */
694    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
695    /**
696     * Whether or not system app permissions should be promoted from install to runtime.
697     */
698    boolean mPromoteSystemApps;
699
700    @GuardedBy("mPackages")
701    final Settings mSettings;
702
703    /**
704     * Set of package names that are currently "frozen", which means active
705     * surgery is being done on the code/data for that package. The platform
706     * will refuse to launch frozen packages to avoid race conditions.
707     *
708     * @see PackageFreezer
709     */
710    @GuardedBy("mPackages")
711    final ArraySet<String> mFrozenPackages = new ArraySet<>();
712
713    final ProtectedPackages mProtectedPackages;
714
715    boolean mFirstBoot;
716
717    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
718
719    // System configuration read by SystemConfig.
720    final int[] mGlobalGids;
721    final SparseArray<ArraySet<String>> mSystemPermissions;
722    @GuardedBy("mAvailableFeatures")
723    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
724
725    // If mac_permissions.xml was found for seinfo labeling.
726    boolean mFoundPolicyFile;
727
728    private final InstantAppRegistry mInstantAppRegistry;
729
730    @GuardedBy("mPackages")
731    int mChangedPackagesSequenceNumber;
732    /**
733     * List of changed [installed, removed or updated] packages.
734     * mapping from user id -> sequence number -> package name
735     */
736    @GuardedBy("mPackages")
737    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
738    /**
739     * The sequence number of the last change to a package.
740     * mapping from user id -> package name -> sequence number
741     */
742    @GuardedBy("mPackages")
743    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
744
745    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
746        @Override public boolean hasFeature(String feature) {
747            return PackageManagerService.this.hasSystemFeature(feature, 0);
748        }
749    };
750
751    public static final class SharedLibraryEntry {
752        public final String path;
753        public final String apk;
754        public final SharedLibraryInfo info;
755
756        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
757                String declaringPackageName, int declaringPackageVersionCode) {
758            path = _path;
759            apk = _apk;
760            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
761                    declaringPackageName, declaringPackageVersionCode), null);
762        }
763    }
764
765    // Currently known shared libraries.
766    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
767    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
768            new ArrayMap<>();
769
770    // All available activities, for your resolving pleasure.
771    final ActivityIntentResolver mActivities =
772            new ActivityIntentResolver();
773
774    // All available receivers, for your resolving pleasure.
775    final ActivityIntentResolver mReceivers =
776            new ActivityIntentResolver();
777
778    // All available services, for your resolving pleasure.
779    final ServiceIntentResolver mServices = new ServiceIntentResolver();
780
781    // All available providers, for your resolving pleasure.
782    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
783
784    // Mapping from provider base names (first directory in content URI codePath)
785    // to the provider information.
786    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
787            new ArrayMap<String, PackageParser.Provider>();
788
789    // Mapping from instrumentation class names to info about them.
790    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
791            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
792
793    // Mapping from permission names to info about them.
794    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
795            new ArrayMap<String, PackageParser.PermissionGroup>();
796
797    // Packages whose data we have transfered into another package, thus
798    // should no longer exist.
799    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
800
801    // Broadcast actions that are only available to the system.
802    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
803
804    /** List of packages waiting for verification. */
805    final SparseArray<PackageVerificationState> mPendingVerification
806            = new SparseArray<PackageVerificationState>();
807
808    /** Set of packages associated with each app op permission. */
809    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
810
811    final PackageInstallerService mInstallerService;
812
813    private final PackageDexOptimizer mPackageDexOptimizer;
814    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
815    // is used by other apps).
816    private final DexManager mDexManager;
817
818    private AtomicInteger mNextMoveId = new AtomicInteger();
819    private final MoveCallbacks mMoveCallbacks;
820
821    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
822
823    // Cache of users who need badging.
824    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
825
826    /** Token for keys in mPendingVerification. */
827    private int mPendingVerificationToken = 0;
828
829    volatile boolean mSystemReady;
830    volatile boolean mSafeMode;
831    volatile boolean mHasSystemUidErrors;
832
833    ApplicationInfo mAndroidApplication;
834    final ActivityInfo mResolveActivity = new ActivityInfo();
835    final ResolveInfo mResolveInfo = new ResolveInfo();
836    ComponentName mResolveComponentName;
837    PackageParser.Package mPlatformPackage;
838    ComponentName mCustomResolverComponentName;
839
840    boolean mResolverReplaced = false;
841
842    private final @Nullable ComponentName mIntentFilterVerifierComponent;
843    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
844
845    private int mIntentFilterVerificationToken = 0;
846
847    /** The service connection to the ephemeral resolver */
848    final EphemeralResolverConnection mInstantAppResolverConnection;
849    /** Component used to show resolver settings for Instant Apps */
850    final ComponentName mInstantAppResolverSettingsComponent;
851
852    /** Component used to install ephemeral applications */
853    ComponentName mInstantAppInstallerComponent;
854    ActivityInfo mInstantAppInstallerActivity;
855    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
856
857    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
858            = new SparseArray<IntentFilterVerificationState>();
859
860    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
861
862    // List of packages names to keep cached, even if they are uninstalled for all users
863    private List<String> mKeepUninstalledPackages;
864
865    private UserManagerInternal mUserManagerInternal;
866
867    private DeviceIdleController.LocalService mDeviceIdleController;
868
869    private File mCacheDir;
870
871    private ArraySet<String> mPrivappPermissionsViolations;
872
873    private Future<?> mPrepareAppDataFuture;
874
875    private static class IFVerificationParams {
876        PackageParser.Package pkg;
877        boolean replacing;
878        int userId;
879        int verifierUid;
880
881        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
882                int _userId, int _verifierUid) {
883            pkg = _pkg;
884            replacing = _replacing;
885            userId = _userId;
886            replacing = _replacing;
887            verifierUid = _verifierUid;
888        }
889    }
890
891    private interface IntentFilterVerifier<T extends IntentFilter> {
892        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
893                                               T filter, String packageName);
894        void startVerifications(int userId);
895        void receiveVerificationResponse(int verificationId);
896    }
897
898    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
899        private Context mContext;
900        private ComponentName mIntentFilterVerifierComponent;
901        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
902
903        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
904            mContext = context;
905            mIntentFilterVerifierComponent = verifierComponent;
906        }
907
908        private String getDefaultScheme() {
909            return IntentFilter.SCHEME_HTTPS;
910        }
911
912        @Override
913        public void startVerifications(int userId) {
914            // Launch verifications requests
915            int count = mCurrentIntentFilterVerifications.size();
916            for (int n=0; n<count; n++) {
917                int verificationId = mCurrentIntentFilterVerifications.get(n);
918                final IntentFilterVerificationState ivs =
919                        mIntentFilterVerificationStates.get(verificationId);
920
921                String packageName = ivs.getPackageName();
922
923                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
924                final int filterCount = filters.size();
925                ArraySet<String> domainsSet = new ArraySet<>();
926                for (int m=0; m<filterCount; m++) {
927                    PackageParser.ActivityIntentInfo filter = filters.get(m);
928                    domainsSet.addAll(filter.getHostsList());
929                }
930                synchronized (mPackages) {
931                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
932                            packageName, domainsSet) != null) {
933                        scheduleWriteSettingsLocked();
934                    }
935                }
936                sendVerificationRequest(userId, verificationId, ivs);
937            }
938            mCurrentIntentFilterVerifications.clear();
939        }
940
941        private void sendVerificationRequest(int userId, int verificationId,
942                IntentFilterVerificationState ivs) {
943
944            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
945            verificationIntent.putExtra(
946                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
947                    verificationId);
948            verificationIntent.putExtra(
949                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
950                    getDefaultScheme());
951            verificationIntent.putExtra(
952                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
953                    ivs.getHostsString());
954            verificationIntent.putExtra(
955                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
956                    ivs.getPackageName());
957            verificationIntent.setComponent(mIntentFilterVerifierComponent);
958            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
959
960            UserHandle user = new UserHandle(userId);
961            mContext.sendBroadcastAsUser(verificationIntent, user);
962            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
963                    "Sending IntentFilter verification broadcast");
964        }
965
966        public void receiveVerificationResponse(int verificationId) {
967            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
968
969            final boolean verified = ivs.isVerified();
970
971            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
972            final int count = filters.size();
973            if (DEBUG_DOMAIN_VERIFICATION) {
974                Slog.i(TAG, "Received verification response " + verificationId
975                        + " for " + count + " filters, verified=" + verified);
976            }
977            for (int n=0; n<count; n++) {
978                PackageParser.ActivityIntentInfo filter = filters.get(n);
979                filter.setVerified(verified);
980
981                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
982                        + " verified with result:" + verified + " and hosts:"
983                        + ivs.getHostsString());
984            }
985
986            mIntentFilterVerificationStates.remove(verificationId);
987
988            final String packageName = ivs.getPackageName();
989            IntentFilterVerificationInfo ivi = null;
990
991            synchronized (mPackages) {
992                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
993            }
994            if (ivi == null) {
995                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
996                        + verificationId + " packageName:" + packageName);
997                return;
998            }
999            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1000                    "Updating IntentFilterVerificationInfo for package " + packageName
1001                            +" verificationId:" + verificationId);
1002
1003            synchronized (mPackages) {
1004                if (verified) {
1005                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1006                } else {
1007                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1008                }
1009                scheduleWriteSettingsLocked();
1010
1011                final int userId = ivs.getUserId();
1012                if (userId != UserHandle.USER_ALL) {
1013                    final int userStatus =
1014                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1015
1016                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1017                    boolean needUpdate = false;
1018
1019                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1020                    // already been set by the User thru the Disambiguation dialog
1021                    switch (userStatus) {
1022                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1023                            if (verified) {
1024                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1025                            } else {
1026                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1027                            }
1028                            needUpdate = true;
1029                            break;
1030
1031                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1032                            if (verified) {
1033                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1034                                needUpdate = true;
1035                            }
1036                            break;
1037
1038                        default:
1039                            // Nothing to do
1040                    }
1041
1042                    if (needUpdate) {
1043                        mSettings.updateIntentFilterVerificationStatusLPw(
1044                                packageName, updatedStatus, userId);
1045                        scheduleWritePackageRestrictionsLocked(userId);
1046                    }
1047                }
1048            }
1049        }
1050
1051        @Override
1052        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1053                    ActivityIntentInfo filter, String packageName) {
1054            if (!hasValidDomains(filter)) {
1055                return false;
1056            }
1057            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1058            if (ivs == null) {
1059                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1060                        packageName);
1061            }
1062            if (DEBUG_DOMAIN_VERIFICATION) {
1063                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1064            }
1065            ivs.addFilter(filter);
1066            return true;
1067        }
1068
1069        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1070                int userId, int verificationId, String packageName) {
1071            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1072                    verifierUid, userId, packageName);
1073            ivs.setPendingState();
1074            synchronized (mPackages) {
1075                mIntentFilterVerificationStates.append(verificationId, ivs);
1076                mCurrentIntentFilterVerifications.add(verificationId);
1077            }
1078            return ivs;
1079        }
1080    }
1081
1082    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1083        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1084                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1085                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1086    }
1087
1088    // Set of pending broadcasts for aggregating enable/disable of components.
1089    static class PendingPackageBroadcasts {
1090        // for each user id, a map of <package name -> components within that package>
1091        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1092
1093        public PendingPackageBroadcasts() {
1094            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1095        }
1096
1097        public ArrayList<String> get(int userId, String packageName) {
1098            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1099            return packages.get(packageName);
1100        }
1101
1102        public void put(int userId, String packageName, ArrayList<String> components) {
1103            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1104            packages.put(packageName, components);
1105        }
1106
1107        public void remove(int userId, String packageName) {
1108            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1109            if (packages != null) {
1110                packages.remove(packageName);
1111            }
1112        }
1113
1114        public void remove(int userId) {
1115            mUidMap.remove(userId);
1116        }
1117
1118        public int userIdCount() {
1119            return mUidMap.size();
1120        }
1121
1122        public int userIdAt(int n) {
1123            return mUidMap.keyAt(n);
1124        }
1125
1126        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1127            return mUidMap.get(userId);
1128        }
1129
1130        public int size() {
1131            // total number of pending broadcast entries across all userIds
1132            int num = 0;
1133            for (int i = 0; i< mUidMap.size(); i++) {
1134                num += mUidMap.valueAt(i).size();
1135            }
1136            return num;
1137        }
1138
1139        public void clear() {
1140            mUidMap.clear();
1141        }
1142
1143        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1144            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1145            if (map == null) {
1146                map = new ArrayMap<String, ArrayList<String>>();
1147                mUidMap.put(userId, map);
1148            }
1149            return map;
1150        }
1151    }
1152    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1153
1154    // Service Connection to remote media container service to copy
1155    // package uri's from external media onto secure containers
1156    // or internal storage.
1157    private IMediaContainerService mContainerService = null;
1158
1159    static final int SEND_PENDING_BROADCAST = 1;
1160    static final int MCS_BOUND = 3;
1161    static final int END_COPY = 4;
1162    static final int INIT_COPY = 5;
1163    static final int MCS_UNBIND = 6;
1164    static final int START_CLEANING_PACKAGE = 7;
1165    static final int FIND_INSTALL_LOC = 8;
1166    static final int POST_INSTALL = 9;
1167    static final int MCS_RECONNECT = 10;
1168    static final int MCS_GIVE_UP = 11;
1169    static final int UPDATED_MEDIA_STATUS = 12;
1170    static final int WRITE_SETTINGS = 13;
1171    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1172    static final int PACKAGE_VERIFIED = 15;
1173    static final int CHECK_PENDING_VERIFICATION = 16;
1174    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1175    static final int INTENT_FILTER_VERIFIED = 18;
1176    static final int WRITE_PACKAGE_LIST = 19;
1177    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1178
1179    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1180
1181    // Delay time in millisecs
1182    static final int BROADCAST_DELAY = 10 * 1000;
1183
1184    static UserManagerService sUserManager;
1185
1186    // Stores a list of users whose package restrictions file needs to be updated
1187    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1188
1189    final private DefaultContainerConnection mDefContainerConn =
1190            new DefaultContainerConnection();
1191    class DefaultContainerConnection implements ServiceConnection {
1192        public void onServiceConnected(ComponentName name, IBinder service) {
1193            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1194            final IMediaContainerService imcs = IMediaContainerService.Stub
1195                    .asInterface(Binder.allowBlocking(service));
1196            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1197        }
1198
1199        public void onServiceDisconnected(ComponentName name) {
1200            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1201        }
1202    }
1203
1204    // Recordkeeping of restore-after-install operations that are currently in flight
1205    // between the Package Manager and the Backup Manager
1206    static class PostInstallData {
1207        public InstallArgs args;
1208        public PackageInstalledInfo res;
1209
1210        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1211            args = _a;
1212            res = _r;
1213        }
1214    }
1215
1216    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1217    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1218
1219    // XML tags for backup/restore of various bits of state
1220    private static final String TAG_PREFERRED_BACKUP = "pa";
1221    private static final String TAG_DEFAULT_APPS = "da";
1222    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1223
1224    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1225    private static final String TAG_ALL_GRANTS = "rt-grants";
1226    private static final String TAG_GRANT = "grant";
1227    private static final String ATTR_PACKAGE_NAME = "pkg";
1228
1229    private static final String TAG_PERMISSION = "perm";
1230    private static final String ATTR_PERMISSION_NAME = "name";
1231    private static final String ATTR_IS_GRANTED = "g";
1232    private static final String ATTR_USER_SET = "set";
1233    private static final String ATTR_USER_FIXED = "fixed";
1234    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1235
1236    // System/policy permission grants are not backed up
1237    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1238            FLAG_PERMISSION_POLICY_FIXED
1239            | FLAG_PERMISSION_SYSTEM_FIXED
1240            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1241
1242    // And we back up these user-adjusted states
1243    private static final int USER_RUNTIME_GRANT_MASK =
1244            FLAG_PERMISSION_USER_SET
1245            | FLAG_PERMISSION_USER_FIXED
1246            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1247
1248    final @Nullable String mRequiredVerifierPackage;
1249    final @NonNull String mRequiredInstallerPackage;
1250    final @NonNull String mRequiredUninstallerPackage;
1251    final @Nullable String mSetupWizardPackage;
1252    final @Nullable String mStorageManagerPackage;
1253    final @NonNull String mServicesSystemSharedLibraryPackageName;
1254    final @NonNull String mSharedSystemSharedLibraryPackageName;
1255
1256    final boolean mPermissionReviewRequired;
1257
1258    private final PackageUsage mPackageUsage = new PackageUsage();
1259    private final CompilerStats mCompilerStats = new CompilerStats();
1260
1261    class PackageHandler extends Handler {
1262        private boolean mBound = false;
1263        final ArrayList<HandlerParams> mPendingInstalls =
1264            new ArrayList<HandlerParams>();
1265
1266        private boolean connectToService() {
1267            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1268                    " DefaultContainerService");
1269            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1270            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1271            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1272                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1273                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1274                mBound = true;
1275                return true;
1276            }
1277            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1278            return false;
1279        }
1280
1281        private void disconnectService() {
1282            mContainerService = null;
1283            mBound = false;
1284            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1285            mContext.unbindService(mDefContainerConn);
1286            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1287        }
1288
1289        PackageHandler(Looper looper) {
1290            super(looper);
1291        }
1292
1293        public void handleMessage(Message msg) {
1294            try {
1295                doHandleMessage(msg);
1296            } finally {
1297                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1298            }
1299        }
1300
1301        void doHandleMessage(Message msg) {
1302            switch (msg.what) {
1303                case INIT_COPY: {
1304                    HandlerParams params = (HandlerParams) msg.obj;
1305                    int idx = mPendingInstalls.size();
1306                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1307                    // If a bind was already initiated we dont really
1308                    // need to do anything. The pending install
1309                    // will be processed later on.
1310                    if (!mBound) {
1311                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1312                                System.identityHashCode(mHandler));
1313                        // If this is the only one pending we might
1314                        // have to bind to the service again.
1315                        if (!connectToService()) {
1316                            Slog.e(TAG, "Failed to bind to media container service");
1317                            params.serviceError();
1318                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1319                                    System.identityHashCode(mHandler));
1320                            if (params.traceMethod != null) {
1321                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1322                                        params.traceCookie);
1323                            }
1324                            return;
1325                        } else {
1326                            // Once we bind to the service, the first
1327                            // pending request will be processed.
1328                            mPendingInstalls.add(idx, params);
1329                        }
1330                    } else {
1331                        mPendingInstalls.add(idx, params);
1332                        // Already bound to the service. Just make
1333                        // sure we trigger off processing the first request.
1334                        if (idx == 0) {
1335                            mHandler.sendEmptyMessage(MCS_BOUND);
1336                        }
1337                    }
1338                    break;
1339                }
1340                case MCS_BOUND: {
1341                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1342                    if (msg.obj != null) {
1343                        mContainerService = (IMediaContainerService) msg.obj;
1344                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1345                                System.identityHashCode(mHandler));
1346                    }
1347                    if (mContainerService == null) {
1348                        if (!mBound) {
1349                            // Something seriously wrong since we are not bound and we are not
1350                            // waiting for connection. Bail out.
1351                            Slog.e(TAG, "Cannot bind to media container service");
1352                            for (HandlerParams params : mPendingInstalls) {
1353                                // Indicate service bind error
1354                                params.serviceError();
1355                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1356                                        System.identityHashCode(params));
1357                                if (params.traceMethod != null) {
1358                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1359                                            params.traceMethod, params.traceCookie);
1360                                }
1361                                return;
1362                            }
1363                            mPendingInstalls.clear();
1364                        } else {
1365                            Slog.w(TAG, "Waiting to connect to media container service");
1366                        }
1367                    } else if (mPendingInstalls.size() > 0) {
1368                        HandlerParams params = mPendingInstalls.get(0);
1369                        if (params != null) {
1370                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1371                                    System.identityHashCode(params));
1372                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1373                            if (params.startCopy()) {
1374                                // We are done...  look for more work or to
1375                                // go idle.
1376                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1377                                        "Checking for more work or unbind...");
1378                                // Delete pending install
1379                                if (mPendingInstalls.size() > 0) {
1380                                    mPendingInstalls.remove(0);
1381                                }
1382                                if (mPendingInstalls.size() == 0) {
1383                                    if (mBound) {
1384                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1385                                                "Posting delayed MCS_UNBIND");
1386                                        removeMessages(MCS_UNBIND);
1387                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1388                                        // Unbind after a little delay, to avoid
1389                                        // continual thrashing.
1390                                        sendMessageDelayed(ubmsg, 10000);
1391                                    }
1392                                } else {
1393                                    // There are more pending requests in queue.
1394                                    // Just post MCS_BOUND message to trigger processing
1395                                    // of next pending install.
1396                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1397                                            "Posting MCS_BOUND for next work");
1398                                    mHandler.sendEmptyMessage(MCS_BOUND);
1399                                }
1400                            }
1401                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1402                        }
1403                    } else {
1404                        // Should never happen ideally.
1405                        Slog.w(TAG, "Empty queue");
1406                    }
1407                    break;
1408                }
1409                case MCS_RECONNECT: {
1410                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1411                    if (mPendingInstalls.size() > 0) {
1412                        if (mBound) {
1413                            disconnectService();
1414                        }
1415                        if (!connectToService()) {
1416                            Slog.e(TAG, "Failed to bind to media container service");
1417                            for (HandlerParams params : mPendingInstalls) {
1418                                // Indicate service bind error
1419                                params.serviceError();
1420                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1421                                        System.identityHashCode(params));
1422                            }
1423                            mPendingInstalls.clear();
1424                        }
1425                    }
1426                    break;
1427                }
1428                case MCS_UNBIND: {
1429                    // If there is no actual work left, then time to unbind.
1430                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1431
1432                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1433                        if (mBound) {
1434                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1435
1436                            disconnectService();
1437                        }
1438                    } else if (mPendingInstalls.size() > 0) {
1439                        // There are more pending requests in queue.
1440                        // Just post MCS_BOUND message to trigger processing
1441                        // of next pending install.
1442                        mHandler.sendEmptyMessage(MCS_BOUND);
1443                    }
1444
1445                    break;
1446                }
1447                case MCS_GIVE_UP: {
1448                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1449                    HandlerParams params = mPendingInstalls.remove(0);
1450                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1451                            System.identityHashCode(params));
1452                    break;
1453                }
1454                case SEND_PENDING_BROADCAST: {
1455                    String packages[];
1456                    ArrayList<String> components[];
1457                    int size = 0;
1458                    int uids[];
1459                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1460                    synchronized (mPackages) {
1461                        if (mPendingBroadcasts == null) {
1462                            return;
1463                        }
1464                        size = mPendingBroadcasts.size();
1465                        if (size <= 0) {
1466                            // Nothing to be done. Just return
1467                            return;
1468                        }
1469                        packages = new String[size];
1470                        components = new ArrayList[size];
1471                        uids = new int[size];
1472                        int i = 0;  // filling out the above arrays
1473
1474                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1475                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1476                            Iterator<Map.Entry<String, ArrayList<String>>> it
1477                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1478                                            .entrySet().iterator();
1479                            while (it.hasNext() && i < size) {
1480                                Map.Entry<String, ArrayList<String>> ent = it.next();
1481                                packages[i] = ent.getKey();
1482                                components[i] = ent.getValue();
1483                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1484                                uids[i] = (ps != null)
1485                                        ? UserHandle.getUid(packageUserId, ps.appId)
1486                                        : -1;
1487                                i++;
1488                            }
1489                        }
1490                        size = i;
1491                        mPendingBroadcasts.clear();
1492                    }
1493                    // Send broadcasts
1494                    for (int i = 0; i < size; i++) {
1495                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1496                    }
1497                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1498                    break;
1499                }
1500                case START_CLEANING_PACKAGE: {
1501                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1502                    final String packageName = (String)msg.obj;
1503                    final int userId = msg.arg1;
1504                    final boolean andCode = msg.arg2 != 0;
1505                    synchronized (mPackages) {
1506                        if (userId == UserHandle.USER_ALL) {
1507                            int[] users = sUserManager.getUserIds();
1508                            for (int user : users) {
1509                                mSettings.addPackageToCleanLPw(
1510                                        new PackageCleanItem(user, packageName, andCode));
1511                            }
1512                        } else {
1513                            mSettings.addPackageToCleanLPw(
1514                                    new PackageCleanItem(userId, packageName, andCode));
1515                        }
1516                    }
1517                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1518                    startCleaningPackages();
1519                } break;
1520                case POST_INSTALL: {
1521                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1522
1523                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1524                    final boolean didRestore = (msg.arg2 != 0);
1525                    mRunningInstalls.delete(msg.arg1);
1526
1527                    if (data != null) {
1528                        InstallArgs args = data.args;
1529                        PackageInstalledInfo parentRes = data.res;
1530
1531                        final boolean grantPermissions = (args.installFlags
1532                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1533                        final boolean killApp = (args.installFlags
1534                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1535                        final String[] grantedPermissions = args.installGrantPermissions;
1536
1537                        // Handle the parent package
1538                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1539                                grantedPermissions, didRestore, args.installerPackageName,
1540                                args.observer);
1541
1542                        // Handle the child packages
1543                        final int childCount = (parentRes.addedChildPackages != null)
1544                                ? parentRes.addedChildPackages.size() : 0;
1545                        for (int i = 0; i < childCount; i++) {
1546                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1547                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1548                                    grantedPermissions, false, args.installerPackageName,
1549                                    args.observer);
1550                        }
1551
1552                        // Log tracing if needed
1553                        if (args.traceMethod != null) {
1554                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1555                                    args.traceCookie);
1556                        }
1557                    } else {
1558                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1559                    }
1560
1561                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1562                } break;
1563                case UPDATED_MEDIA_STATUS: {
1564                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1565                    boolean reportStatus = msg.arg1 == 1;
1566                    boolean doGc = msg.arg2 == 1;
1567                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1568                    if (doGc) {
1569                        // Force a gc to clear up stale containers.
1570                        Runtime.getRuntime().gc();
1571                    }
1572                    if (msg.obj != null) {
1573                        @SuppressWarnings("unchecked")
1574                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1575                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1576                        // Unload containers
1577                        unloadAllContainers(args);
1578                    }
1579                    if (reportStatus) {
1580                        try {
1581                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1582                                    "Invoking StorageManagerService call back");
1583                            PackageHelper.getStorageManager().finishMediaUpdate();
1584                        } catch (RemoteException e) {
1585                            Log.e(TAG, "StorageManagerService not running?");
1586                        }
1587                    }
1588                } break;
1589                case WRITE_SETTINGS: {
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1591                    synchronized (mPackages) {
1592                        removeMessages(WRITE_SETTINGS);
1593                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1594                        mSettings.writeLPr();
1595                        mDirtyUsers.clear();
1596                    }
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1598                } break;
1599                case WRITE_PACKAGE_RESTRICTIONS: {
1600                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1601                    synchronized (mPackages) {
1602                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1603                        for (int userId : mDirtyUsers) {
1604                            mSettings.writePackageRestrictionsLPr(userId);
1605                        }
1606                        mDirtyUsers.clear();
1607                    }
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1609                } break;
1610                case WRITE_PACKAGE_LIST: {
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1612                    synchronized (mPackages) {
1613                        removeMessages(WRITE_PACKAGE_LIST);
1614                        mSettings.writePackageListLPr(msg.arg1);
1615                    }
1616                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1617                } break;
1618                case CHECK_PENDING_VERIFICATION: {
1619                    final int verificationId = msg.arg1;
1620                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1621
1622                    if ((state != null) && !state.timeoutExtended()) {
1623                        final InstallArgs args = state.getInstallArgs();
1624                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1625
1626                        Slog.i(TAG, "Verification timed out for " + originUri);
1627                        mPendingVerification.remove(verificationId);
1628
1629                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1630
1631                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1632                            Slog.i(TAG, "Continuing with installation of " + originUri);
1633                            state.setVerifierResponse(Binder.getCallingUid(),
1634                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1635                            broadcastPackageVerified(verificationId, originUri,
1636                                    PackageManager.VERIFICATION_ALLOW,
1637                                    state.getInstallArgs().getUser());
1638                            try {
1639                                ret = args.copyApk(mContainerService, true);
1640                            } catch (RemoteException e) {
1641                                Slog.e(TAG, "Could not contact the ContainerService");
1642                            }
1643                        } else {
1644                            broadcastPackageVerified(verificationId, originUri,
1645                                    PackageManager.VERIFICATION_REJECT,
1646                                    state.getInstallArgs().getUser());
1647                        }
1648
1649                        Trace.asyncTraceEnd(
1650                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1651
1652                        processPendingInstall(args, ret);
1653                        mHandler.sendEmptyMessage(MCS_UNBIND);
1654                    }
1655                    break;
1656                }
1657                case PACKAGE_VERIFIED: {
1658                    final int verificationId = msg.arg1;
1659
1660                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1661                    if (state == null) {
1662                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1663                        break;
1664                    }
1665
1666                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1667
1668                    state.setVerifierResponse(response.callerUid, response.code);
1669
1670                    if (state.isVerificationComplete()) {
1671                        mPendingVerification.remove(verificationId);
1672
1673                        final InstallArgs args = state.getInstallArgs();
1674                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1675
1676                        int ret;
1677                        if (state.isInstallAllowed()) {
1678                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1679                            broadcastPackageVerified(verificationId, originUri,
1680                                    response.code, state.getInstallArgs().getUser());
1681                            try {
1682                                ret = args.copyApk(mContainerService, true);
1683                            } catch (RemoteException e) {
1684                                Slog.e(TAG, "Could not contact the ContainerService");
1685                            }
1686                        } else {
1687                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1688                        }
1689
1690                        Trace.asyncTraceEnd(
1691                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1692
1693                        processPendingInstall(args, ret);
1694                        mHandler.sendEmptyMessage(MCS_UNBIND);
1695                    }
1696
1697                    break;
1698                }
1699                case START_INTENT_FILTER_VERIFICATIONS: {
1700                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1701                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1702                            params.replacing, params.pkg);
1703                    break;
1704                }
1705                case INTENT_FILTER_VERIFIED: {
1706                    final int verificationId = msg.arg1;
1707
1708                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1709                            verificationId);
1710                    if (state == null) {
1711                        Slog.w(TAG, "Invalid IntentFilter verification token "
1712                                + verificationId + " received");
1713                        break;
1714                    }
1715
1716                    final int userId = state.getUserId();
1717
1718                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1719                            "Processing IntentFilter verification with token:"
1720                            + verificationId + " and userId:" + userId);
1721
1722                    final IntentFilterVerificationResponse response =
1723                            (IntentFilterVerificationResponse) msg.obj;
1724
1725                    state.setVerifierResponse(response.callerUid, response.code);
1726
1727                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1728                            "IntentFilter verification with token:" + verificationId
1729                            + " and userId:" + userId
1730                            + " is settings verifier response with response code:"
1731                            + response.code);
1732
1733                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1734                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1735                                + response.getFailedDomainsString());
1736                    }
1737
1738                    if (state.isVerificationComplete()) {
1739                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1740                    } else {
1741                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1742                                "IntentFilter verification with token:" + verificationId
1743                                + " was not said to be complete");
1744                    }
1745
1746                    break;
1747                }
1748                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1749                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1750                            mInstantAppResolverConnection,
1751                            (InstantAppRequest) msg.obj,
1752                            mInstantAppInstallerActivity,
1753                            mHandler);
1754                }
1755            }
1756        }
1757    }
1758
1759    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1760            boolean killApp, String[] grantedPermissions,
1761            boolean launchedForRestore, String installerPackage,
1762            IPackageInstallObserver2 installObserver) {
1763        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1764            // Send the removed broadcasts
1765            if (res.removedInfo != null) {
1766                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1767            }
1768
1769            // Now that we successfully installed the package, grant runtime
1770            // permissions if requested before broadcasting the install. Also
1771            // for legacy apps in permission review mode we clear the permission
1772            // review flag which is used to emulate runtime permissions for
1773            // legacy apps.
1774            if (grantPermissions) {
1775                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1776            }
1777
1778            final boolean update = res.removedInfo != null
1779                    && res.removedInfo.removedPackage != null;
1780
1781            // If this is the first time we have child packages for a disabled privileged
1782            // app that had no children, we grant requested runtime permissions to the new
1783            // children if the parent on the system image had them already granted.
1784            if (res.pkg.parentPackage != null) {
1785                synchronized (mPackages) {
1786                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1787                }
1788            }
1789
1790            synchronized (mPackages) {
1791                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1792            }
1793
1794            final String packageName = res.pkg.applicationInfo.packageName;
1795
1796            // Determine the set of users who are adding this package for
1797            // the first time vs. those who are seeing an update.
1798            int[] firstUsers = EMPTY_INT_ARRAY;
1799            int[] updateUsers = EMPTY_INT_ARRAY;
1800            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1801            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1802            for (int newUser : res.newUsers) {
1803                if (ps.getInstantApp(newUser)) {
1804                    continue;
1805                }
1806                if (allNewUsers) {
1807                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1808                    continue;
1809                }
1810                boolean isNew = true;
1811                for (int origUser : res.origUsers) {
1812                    if (origUser == newUser) {
1813                        isNew = false;
1814                        break;
1815                    }
1816                }
1817                if (isNew) {
1818                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1819                } else {
1820                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1821                }
1822            }
1823
1824            // Send installed broadcasts if the package is not a static shared lib.
1825            if (res.pkg.staticSharedLibName == null) {
1826                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1827
1828                // Send added for users that see the package for the first time
1829                // sendPackageAddedForNewUsers also deals with system apps
1830                int appId = UserHandle.getAppId(res.uid);
1831                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1832                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1833
1834                // Send added for users that don't see the package for the first time
1835                Bundle extras = new Bundle(1);
1836                extras.putInt(Intent.EXTRA_UID, res.uid);
1837                if (update) {
1838                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1839                }
1840                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1841                        extras, 0 /*flags*/, null /*targetPackage*/,
1842                        null /*finishedReceiver*/, updateUsers);
1843
1844                // Send replaced for users that don't see the package for the first time
1845                if (update) {
1846                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1847                            packageName, extras, 0 /*flags*/,
1848                            null /*targetPackage*/, null /*finishedReceiver*/,
1849                            updateUsers);
1850                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1851                            null /*package*/, null /*extras*/, 0 /*flags*/,
1852                            packageName /*targetPackage*/,
1853                            null /*finishedReceiver*/, updateUsers);
1854                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1855                    // First-install and we did a restore, so we're responsible for the
1856                    // first-launch broadcast.
1857                    if (DEBUG_BACKUP) {
1858                        Slog.i(TAG, "Post-restore of " + packageName
1859                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1860                    }
1861                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1862                }
1863
1864                // Send broadcast package appeared if forward locked/external for all users
1865                // treat asec-hosted packages like removable media on upgrade
1866                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1867                    if (DEBUG_INSTALL) {
1868                        Slog.i(TAG, "upgrading pkg " + res.pkg
1869                                + " is ASEC-hosted -> AVAILABLE");
1870                    }
1871                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1872                    ArrayList<String> pkgList = new ArrayList<>(1);
1873                    pkgList.add(packageName);
1874                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1875                }
1876            }
1877
1878            // Work that needs to happen on first install within each user
1879            if (firstUsers != null && firstUsers.length > 0) {
1880                synchronized (mPackages) {
1881                    for (int userId : firstUsers) {
1882                        // If this app is a browser and it's newly-installed for some
1883                        // users, clear any default-browser state in those users. The
1884                        // app's nature doesn't depend on the user, so we can just check
1885                        // its browser nature in any user and generalize.
1886                        if (packageIsBrowser(packageName, userId)) {
1887                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1888                        }
1889
1890                        // We may also need to apply pending (restored) runtime
1891                        // permission grants within these users.
1892                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1893                    }
1894                }
1895            }
1896
1897            // Log current value of "unknown sources" setting
1898            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1899                    getUnknownSourcesSettings());
1900
1901            // Force a gc to clear up things
1902            Runtime.getRuntime().gc();
1903
1904            // Remove the replaced package's older resources safely now
1905            // We delete after a gc for applications  on sdcard.
1906            if (res.removedInfo != null && res.removedInfo.args != null) {
1907                synchronized (mInstallLock) {
1908                    res.removedInfo.args.doPostDeleteLI(true);
1909                }
1910            }
1911
1912            // Notify DexManager that the package was installed for new users.
1913            // The updated users should already be indexed and the package code paths
1914            // should not change.
1915            // Don't notify the manager for ephemeral apps as they are not expected to
1916            // survive long enough to benefit of background optimizations.
1917            for (int userId : firstUsers) {
1918                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1919                mDexManager.notifyPackageInstalled(info, userId);
1920            }
1921        }
1922
1923        // If someone is watching installs - notify them
1924        if (installObserver != null) {
1925            try {
1926                Bundle extras = extrasForInstallResult(res);
1927                installObserver.onPackageInstalled(res.name, res.returnCode,
1928                        res.returnMsg, extras);
1929            } catch (RemoteException e) {
1930                Slog.i(TAG, "Observer no longer exists.");
1931            }
1932        }
1933    }
1934
1935    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1936            PackageParser.Package pkg) {
1937        if (pkg.parentPackage == null) {
1938            return;
1939        }
1940        if (pkg.requestedPermissions == null) {
1941            return;
1942        }
1943        final PackageSetting disabledSysParentPs = mSettings
1944                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1945        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1946                || !disabledSysParentPs.isPrivileged()
1947                || (disabledSysParentPs.childPackageNames != null
1948                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1949            return;
1950        }
1951        final int[] allUserIds = sUserManager.getUserIds();
1952        final int permCount = pkg.requestedPermissions.size();
1953        for (int i = 0; i < permCount; i++) {
1954            String permission = pkg.requestedPermissions.get(i);
1955            BasePermission bp = mSettings.mPermissions.get(permission);
1956            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1957                continue;
1958            }
1959            for (int userId : allUserIds) {
1960                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1961                        permission, userId)) {
1962                    grantRuntimePermission(pkg.packageName, permission, userId);
1963                }
1964            }
1965        }
1966    }
1967
1968    private StorageEventListener mStorageListener = new StorageEventListener() {
1969        @Override
1970        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1971            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1972                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1973                    final String volumeUuid = vol.getFsUuid();
1974
1975                    // Clean up any users or apps that were removed or recreated
1976                    // while this volume was missing
1977                    sUserManager.reconcileUsers(volumeUuid);
1978                    reconcileApps(volumeUuid);
1979
1980                    // Clean up any install sessions that expired or were
1981                    // cancelled while this volume was missing
1982                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1983
1984                    loadPrivatePackages(vol);
1985
1986                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1987                    unloadPrivatePackages(vol);
1988                }
1989            }
1990
1991            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1992                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1993                    updateExternalMediaStatus(true, false);
1994                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1995                    updateExternalMediaStatus(false, false);
1996                }
1997            }
1998        }
1999
2000        @Override
2001        public void onVolumeForgotten(String fsUuid) {
2002            if (TextUtils.isEmpty(fsUuid)) {
2003                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2004                return;
2005            }
2006
2007            // Remove any apps installed on the forgotten volume
2008            synchronized (mPackages) {
2009                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2010                for (PackageSetting ps : packages) {
2011                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2012                    deletePackageVersioned(new VersionedPackage(ps.name,
2013                            PackageManager.VERSION_CODE_HIGHEST),
2014                            new LegacyPackageDeleteObserver(null).getBinder(),
2015                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2016                    // Try very hard to release any references to this package
2017                    // so we don't risk the system server being killed due to
2018                    // open FDs
2019                    AttributeCache.instance().removePackage(ps.name);
2020                }
2021
2022                mSettings.onVolumeForgotten(fsUuid);
2023                mSettings.writeLPr();
2024            }
2025        }
2026    };
2027
2028    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2029            String[] grantedPermissions) {
2030        for (int userId : userIds) {
2031            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2032        }
2033    }
2034
2035    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2036            String[] grantedPermissions) {
2037        SettingBase sb = (SettingBase) pkg.mExtras;
2038        if (sb == null) {
2039            return;
2040        }
2041
2042        PermissionsState permissionsState = sb.getPermissionsState();
2043
2044        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2045                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2046
2047        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2048                >= Build.VERSION_CODES.M;
2049
2050        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2051
2052        for (String permission : pkg.requestedPermissions) {
2053            final BasePermission bp;
2054            synchronized (mPackages) {
2055                bp = mSettings.mPermissions.get(permission);
2056            }
2057            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2058                    && (!instantApp || bp.isInstant())
2059                    && (grantedPermissions == null
2060                           || ArrayUtils.contains(grantedPermissions, permission))) {
2061                final int flags = permissionsState.getPermissionFlags(permission, userId);
2062                if (supportsRuntimePermissions) {
2063                    // Installer cannot change immutable permissions.
2064                    if ((flags & immutableFlags) == 0) {
2065                        grantRuntimePermission(pkg.packageName, permission, userId);
2066                    }
2067                } else if (mPermissionReviewRequired) {
2068                    // In permission review mode we clear the review flag when we
2069                    // are asked to install the app with all permissions granted.
2070                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2071                        updatePermissionFlags(permission, pkg.packageName,
2072                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2073                    }
2074                }
2075            }
2076        }
2077    }
2078
2079    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2080        Bundle extras = null;
2081        switch (res.returnCode) {
2082            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2083                extras = new Bundle();
2084                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2085                        res.origPermission);
2086                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2087                        res.origPackage);
2088                break;
2089            }
2090            case PackageManager.INSTALL_SUCCEEDED: {
2091                extras = new Bundle();
2092                extras.putBoolean(Intent.EXTRA_REPLACING,
2093                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2094                break;
2095            }
2096        }
2097        return extras;
2098    }
2099
2100    void scheduleWriteSettingsLocked() {
2101        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2102            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2103        }
2104    }
2105
2106    void scheduleWritePackageListLocked(int userId) {
2107        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2108            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2109            msg.arg1 = userId;
2110            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2111        }
2112    }
2113
2114    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2115        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2116        scheduleWritePackageRestrictionsLocked(userId);
2117    }
2118
2119    void scheduleWritePackageRestrictionsLocked(int userId) {
2120        final int[] userIds = (userId == UserHandle.USER_ALL)
2121                ? sUserManager.getUserIds() : new int[]{userId};
2122        for (int nextUserId : userIds) {
2123            if (!sUserManager.exists(nextUserId)) return;
2124            mDirtyUsers.add(nextUserId);
2125            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2126                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2127            }
2128        }
2129    }
2130
2131    public static PackageManagerService main(Context context, Installer installer,
2132            boolean factoryTest, boolean onlyCore) {
2133        // Self-check for initial settings.
2134        PackageManagerServiceCompilerMapping.checkProperties();
2135
2136        PackageManagerService m = new PackageManagerService(context, installer,
2137                factoryTest, onlyCore);
2138        m.enableSystemUserPackages();
2139        ServiceManager.addService("package", m);
2140        return m;
2141    }
2142
2143    private void enableSystemUserPackages() {
2144        if (!UserManager.isSplitSystemUser()) {
2145            return;
2146        }
2147        // For system user, enable apps based on the following conditions:
2148        // - app is whitelisted or belong to one of these groups:
2149        //   -- system app which has no launcher icons
2150        //   -- system app which has INTERACT_ACROSS_USERS permission
2151        //   -- system IME app
2152        // - app is not in the blacklist
2153        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2154        Set<String> enableApps = new ArraySet<>();
2155        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2156                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2157                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2158        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2159        enableApps.addAll(wlApps);
2160        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2161                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2162        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2163        enableApps.removeAll(blApps);
2164        Log.i(TAG, "Applications installed for system user: " + enableApps);
2165        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2166                UserHandle.SYSTEM);
2167        final int allAppsSize = allAps.size();
2168        synchronized (mPackages) {
2169            for (int i = 0; i < allAppsSize; i++) {
2170                String pName = allAps.get(i);
2171                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2172                // Should not happen, but we shouldn't be failing if it does
2173                if (pkgSetting == null) {
2174                    continue;
2175                }
2176                boolean install = enableApps.contains(pName);
2177                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2178                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2179                            + " for system user");
2180                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2181                }
2182            }
2183            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2184        }
2185    }
2186
2187    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2188        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2189                Context.DISPLAY_SERVICE);
2190        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2191    }
2192
2193    /**
2194     * Requests that files preopted on a secondary system partition be copied to the data partition
2195     * if possible.  Note that the actual copying of the files is accomplished by init for security
2196     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2197     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2198     */
2199    private static void requestCopyPreoptedFiles() {
2200        final int WAIT_TIME_MS = 100;
2201        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2202        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2203            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2204            // We will wait for up to 100 seconds.
2205            final long timeStart = SystemClock.uptimeMillis();
2206            final long timeEnd = timeStart + 100 * 1000;
2207            long timeNow = timeStart;
2208            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2209                try {
2210                    Thread.sleep(WAIT_TIME_MS);
2211                } catch (InterruptedException e) {
2212                    // Do nothing
2213                }
2214                timeNow = SystemClock.uptimeMillis();
2215                if (timeNow > timeEnd) {
2216                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2217                    Slog.wtf(TAG, "cppreopt did not finish!");
2218                    break;
2219                }
2220            }
2221
2222            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2223        }
2224    }
2225
2226    public PackageManagerService(Context context, Installer installer,
2227            boolean factoryTest, boolean onlyCore) {
2228        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2229        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2230        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2231                SystemClock.uptimeMillis());
2232
2233        if (mSdkVersion <= 0) {
2234            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2235        }
2236
2237        mContext = context;
2238
2239        mPermissionReviewRequired = context.getResources().getBoolean(
2240                R.bool.config_permissionReviewRequired);
2241
2242        mFactoryTest = factoryTest;
2243        mOnlyCore = onlyCore;
2244        mMetrics = new DisplayMetrics();
2245        mSettings = new Settings(mPackages);
2246        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2247                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2248        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2249                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2250        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2251                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2252        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2253                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2254        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2255                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2256        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2257                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2258
2259        String separateProcesses = SystemProperties.get("debug.separate_processes");
2260        if (separateProcesses != null && separateProcesses.length() > 0) {
2261            if ("*".equals(separateProcesses)) {
2262                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2263                mSeparateProcesses = null;
2264                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2265            } else {
2266                mDefParseFlags = 0;
2267                mSeparateProcesses = separateProcesses.split(",");
2268                Slog.w(TAG, "Running with debug.separate_processes: "
2269                        + separateProcesses);
2270            }
2271        } else {
2272            mDefParseFlags = 0;
2273            mSeparateProcesses = null;
2274        }
2275
2276        mInstaller = installer;
2277        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2278                "*dexopt*");
2279        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2280        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2281
2282        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2283                FgThread.get().getLooper());
2284
2285        getDefaultDisplayMetrics(context, mMetrics);
2286
2287        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2288        SystemConfig systemConfig = SystemConfig.getInstance();
2289        mGlobalGids = systemConfig.getGlobalGids();
2290        mSystemPermissions = systemConfig.getSystemPermissions();
2291        mAvailableFeatures = systemConfig.getAvailableFeatures();
2292        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2293
2294        mProtectedPackages = new ProtectedPackages(mContext);
2295
2296        synchronized (mInstallLock) {
2297        // writer
2298        synchronized (mPackages) {
2299            mHandlerThread = new ServiceThread(TAG,
2300                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2301            mHandlerThread.start();
2302            mHandler = new PackageHandler(mHandlerThread.getLooper());
2303            mProcessLoggingHandler = new ProcessLoggingHandler();
2304            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2305
2306            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2307            mInstantAppRegistry = new InstantAppRegistry(this);
2308
2309            File dataDir = Environment.getDataDirectory();
2310            mAppInstallDir = new File(dataDir, "app");
2311            mAppLib32InstallDir = new File(dataDir, "app-lib");
2312            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2313            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2314            sUserManager = new UserManagerService(context, this,
2315                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2316
2317            // Propagate permission configuration in to package manager.
2318            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2319                    = systemConfig.getPermissions();
2320            for (int i=0; i<permConfig.size(); i++) {
2321                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2322                BasePermission bp = mSettings.mPermissions.get(perm.name);
2323                if (bp == null) {
2324                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2325                    mSettings.mPermissions.put(perm.name, bp);
2326                }
2327                if (perm.gids != null) {
2328                    bp.setGids(perm.gids, perm.perUser);
2329                }
2330            }
2331
2332            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2333            final int builtInLibCount = libConfig.size();
2334            for (int i = 0; i < builtInLibCount; i++) {
2335                String name = libConfig.keyAt(i);
2336                String path = libConfig.valueAt(i);
2337                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2338                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2339            }
2340
2341            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2342
2343            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2344            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2345            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2346
2347            // Clean up orphaned packages for which the code path doesn't exist
2348            // and they are an update to a system app - caused by bug/32321269
2349            final int packageSettingCount = mSettings.mPackages.size();
2350            for (int i = packageSettingCount - 1; i >= 0; i--) {
2351                PackageSetting ps = mSettings.mPackages.valueAt(i);
2352                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2353                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2354                    mSettings.mPackages.removeAt(i);
2355                    mSettings.enableSystemPackageLPw(ps.name);
2356                }
2357            }
2358
2359            if (mFirstBoot) {
2360                requestCopyPreoptedFiles();
2361            }
2362
2363            String customResolverActivity = Resources.getSystem().getString(
2364                    R.string.config_customResolverActivity);
2365            if (TextUtils.isEmpty(customResolverActivity)) {
2366                customResolverActivity = null;
2367            } else {
2368                mCustomResolverComponentName = ComponentName.unflattenFromString(
2369                        customResolverActivity);
2370            }
2371
2372            long startTime = SystemClock.uptimeMillis();
2373
2374            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2375                    startTime);
2376
2377            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2378            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2379
2380            if (bootClassPath == null) {
2381                Slog.w(TAG, "No BOOTCLASSPATH found!");
2382            }
2383
2384            if (systemServerClassPath == null) {
2385                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2386            }
2387
2388            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2389
2390            final VersionInfo ver = mSettings.getInternalVersion();
2391            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2392            if (mIsUpgrade) {
2393                logCriticalInfo(Log.INFO,
2394                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2395            }
2396
2397            // when upgrading from pre-M, promote system app permissions from install to runtime
2398            mPromoteSystemApps =
2399                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2400
2401            // When upgrading from pre-N, we need to handle package extraction like first boot,
2402            // as there is no profiling data available.
2403            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2404
2405            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2406
2407            // save off the names of pre-existing system packages prior to scanning; we don't
2408            // want to automatically grant runtime permissions for new system apps
2409            if (mPromoteSystemApps) {
2410                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2411                while (pkgSettingIter.hasNext()) {
2412                    PackageSetting ps = pkgSettingIter.next();
2413                    if (isSystemApp(ps)) {
2414                        mExistingSystemPackages.add(ps.name);
2415                    }
2416                }
2417            }
2418
2419            mCacheDir = preparePackageParserCache(mIsUpgrade);
2420
2421            // Set flag to monitor and not change apk file paths when
2422            // scanning install directories.
2423            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2424
2425            if (mIsUpgrade || mFirstBoot) {
2426                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2427            }
2428
2429            // Collect vendor overlay packages. (Do this before scanning any apps.)
2430            // For security and version matching reason, only consider
2431            // overlay packages if they reside in the right directory.
2432            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2433                    | PackageParser.PARSE_IS_SYSTEM
2434                    | PackageParser.PARSE_IS_SYSTEM_DIR
2435                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2436
2437            // Find base frameworks (resource packages without code).
2438            scanDirTracedLI(frameworkDir, mDefParseFlags
2439                    | PackageParser.PARSE_IS_SYSTEM
2440                    | PackageParser.PARSE_IS_SYSTEM_DIR
2441                    | PackageParser.PARSE_IS_PRIVILEGED,
2442                    scanFlags | SCAN_NO_DEX, 0);
2443
2444            // Collected privileged system packages.
2445            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2446            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2447                    | PackageParser.PARSE_IS_SYSTEM
2448                    | PackageParser.PARSE_IS_SYSTEM_DIR
2449                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2450
2451            // Collect ordinary system packages.
2452            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2453            scanDirTracedLI(systemAppDir, mDefParseFlags
2454                    | PackageParser.PARSE_IS_SYSTEM
2455                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2456
2457            // Collect all vendor packages.
2458            File vendorAppDir = new File("/vendor/app");
2459            try {
2460                vendorAppDir = vendorAppDir.getCanonicalFile();
2461            } catch (IOException e) {
2462                // failed to look up canonical path, continue with original one
2463            }
2464            scanDirTracedLI(vendorAppDir, mDefParseFlags
2465                    | PackageParser.PARSE_IS_SYSTEM
2466                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2467
2468            // Collect all OEM packages.
2469            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2470            scanDirTracedLI(oemAppDir, mDefParseFlags
2471                    | PackageParser.PARSE_IS_SYSTEM
2472                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2473
2474            // Prune any system packages that no longer exist.
2475            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2476            if (!mOnlyCore) {
2477                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2478                while (psit.hasNext()) {
2479                    PackageSetting ps = psit.next();
2480
2481                    /*
2482                     * If this is not a system app, it can't be a
2483                     * disable system app.
2484                     */
2485                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2486                        continue;
2487                    }
2488
2489                    /*
2490                     * If the package is scanned, it's not erased.
2491                     */
2492                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2493                    if (scannedPkg != null) {
2494                        /*
2495                         * If the system app is both scanned and in the
2496                         * disabled packages list, then it must have been
2497                         * added via OTA. Remove it from the currently
2498                         * scanned package so the previously user-installed
2499                         * application can be scanned.
2500                         */
2501                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2502                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2503                                    + ps.name + "; removing system app.  Last known codePath="
2504                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2505                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2506                                    + scannedPkg.mVersionCode);
2507                            removePackageLI(scannedPkg, true);
2508                            mExpectingBetter.put(ps.name, ps.codePath);
2509                        }
2510
2511                        continue;
2512                    }
2513
2514                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2515                        psit.remove();
2516                        logCriticalInfo(Log.WARN, "System package " + ps.name
2517                                + " no longer exists; it's data will be wiped");
2518                        // Actual deletion of code and data will be handled by later
2519                        // reconciliation step
2520                    } else {
2521                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2522                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2523                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2524                        }
2525                    }
2526                }
2527            }
2528
2529            //look for any incomplete package installations
2530            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2531            for (int i = 0; i < deletePkgsList.size(); i++) {
2532                // Actual deletion of code and data will be handled by later
2533                // reconciliation step
2534                final String packageName = deletePkgsList.get(i).name;
2535                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2536                synchronized (mPackages) {
2537                    mSettings.removePackageLPw(packageName);
2538                }
2539            }
2540
2541            //delete tmp files
2542            deleteTempPackageFiles();
2543
2544            // Remove any shared userIDs that have no associated packages
2545            mSettings.pruneSharedUsersLPw();
2546
2547            if (!mOnlyCore) {
2548                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2549                        SystemClock.uptimeMillis());
2550                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2551
2552                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2553                        | PackageParser.PARSE_FORWARD_LOCK,
2554                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2555
2556                /**
2557                 * Remove disable package settings for any updated system
2558                 * apps that were removed via an OTA. If they're not a
2559                 * previously-updated app, remove them completely.
2560                 * Otherwise, just revoke their system-level permissions.
2561                 */
2562                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2563                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2564                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2565
2566                    String msg;
2567                    if (deletedPkg == null) {
2568                        msg = "Updated system package " + deletedAppName
2569                                + " no longer exists; it's data will be wiped";
2570                        // Actual deletion of code and data will be handled by later
2571                        // reconciliation step
2572                    } else {
2573                        msg = "Updated system app + " + deletedAppName
2574                                + " no longer present; removing system privileges for "
2575                                + deletedAppName;
2576
2577                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2578
2579                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2580                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2581                    }
2582                    logCriticalInfo(Log.WARN, msg);
2583                }
2584
2585                /**
2586                 * Make sure all system apps that we expected to appear on
2587                 * the userdata partition actually showed up. If they never
2588                 * appeared, crawl back and revive the system version.
2589                 */
2590                for (int i = 0; i < mExpectingBetter.size(); i++) {
2591                    final String packageName = mExpectingBetter.keyAt(i);
2592                    if (!mPackages.containsKey(packageName)) {
2593                        final File scanFile = mExpectingBetter.valueAt(i);
2594
2595                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2596                                + " but never showed up; reverting to system");
2597
2598                        int reparseFlags = mDefParseFlags;
2599                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2600                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2601                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2602                                    | PackageParser.PARSE_IS_PRIVILEGED;
2603                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2604                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2605                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2606                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2607                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2608                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2609                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2610                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2611                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2612                        } else {
2613                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2614                            continue;
2615                        }
2616
2617                        mSettings.enableSystemPackageLPw(packageName);
2618
2619                        try {
2620                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2621                        } catch (PackageManagerException e) {
2622                            Slog.e(TAG, "Failed to parse original system package: "
2623                                    + e.getMessage());
2624                        }
2625                    }
2626                }
2627            }
2628            mExpectingBetter.clear();
2629
2630            // Resolve the storage manager.
2631            mStorageManagerPackage = getStorageManagerPackageName();
2632
2633            // Resolve protected action filters. Only the setup wizard is allowed to
2634            // have a high priority filter for these actions.
2635            mSetupWizardPackage = getSetupWizardPackageName();
2636            if (mProtectedFilters.size() > 0) {
2637                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2638                    Slog.i(TAG, "No setup wizard;"
2639                        + " All protected intents capped to priority 0");
2640                }
2641                for (ActivityIntentInfo filter : mProtectedFilters) {
2642                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2643                        if (DEBUG_FILTERS) {
2644                            Slog.i(TAG, "Found setup wizard;"
2645                                + " allow priority " + filter.getPriority() + ";"
2646                                + " package: " + filter.activity.info.packageName
2647                                + " activity: " + filter.activity.className
2648                                + " priority: " + filter.getPriority());
2649                        }
2650                        // skip setup wizard; allow it to keep the high priority filter
2651                        continue;
2652                    }
2653                    Slog.w(TAG, "Protected action; cap priority to 0;"
2654                            + " package: " + filter.activity.info.packageName
2655                            + " activity: " + filter.activity.className
2656                            + " origPrio: " + filter.getPriority());
2657                    filter.setPriority(0);
2658                }
2659            }
2660            mDeferProtectedFilters = false;
2661            mProtectedFilters.clear();
2662
2663            // Now that we know all of the shared libraries, update all clients to have
2664            // the correct library paths.
2665            updateAllSharedLibrariesLPw(null);
2666
2667            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2668                // NOTE: We ignore potential failures here during a system scan (like
2669                // the rest of the commands above) because there's precious little we
2670                // can do about it. A settings error is reported, though.
2671                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2672            }
2673
2674            // Now that we know all the packages we are keeping,
2675            // read and update their last usage times.
2676            mPackageUsage.read(mPackages);
2677            mCompilerStats.read();
2678
2679            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2680                    SystemClock.uptimeMillis());
2681            Slog.i(TAG, "Time to scan packages: "
2682                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2683                    + " seconds");
2684
2685            // If the platform SDK has changed since the last time we booted,
2686            // we need to re-grant app permission to catch any new ones that
2687            // appear.  This is really a hack, and means that apps can in some
2688            // cases get permissions that the user didn't initially explicitly
2689            // allow...  it would be nice to have some better way to handle
2690            // this situation.
2691            int updateFlags = UPDATE_PERMISSIONS_ALL;
2692            if (ver.sdkVersion != mSdkVersion) {
2693                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2694                        + mSdkVersion + "; regranting permissions for internal storage");
2695                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2696            }
2697            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2698            ver.sdkVersion = mSdkVersion;
2699
2700            // If this is the first boot or an update from pre-M, and it is a normal
2701            // boot, then we need to initialize the default preferred apps across
2702            // all defined users.
2703            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2704                for (UserInfo user : sUserManager.getUsers(true)) {
2705                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2706                    applyFactoryDefaultBrowserLPw(user.id);
2707                    primeDomainVerificationsLPw(user.id);
2708                }
2709            }
2710
2711            // Prepare storage for system user really early during boot,
2712            // since core system apps like SettingsProvider and SystemUI
2713            // can't wait for user to start
2714            final int storageFlags;
2715            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2716                storageFlags = StorageManager.FLAG_STORAGE_DE;
2717            } else {
2718                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2719            }
2720            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2721                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2722                    true /* onlyCoreApps */);
2723            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2724                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "fixup");
2725                try {
2726                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2727                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2728                } catch (InstallerException e) {
2729                    Slog.w(TAG, "Trouble fixing GIDs", e);
2730                }
2731                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2732
2733                if (deferPackages == null || deferPackages.isEmpty()) {
2734                    return;
2735                }
2736                int count = 0;
2737                for (String pkgName : deferPackages) {
2738                    PackageParser.Package pkg = null;
2739                    synchronized (mPackages) {
2740                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2741                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2742                            pkg = ps.pkg;
2743                        }
2744                    }
2745                    if (pkg != null) {
2746                        synchronized (mInstallLock) {
2747                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2748                                    true /* maybeMigrateAppData */);
2749                        }
2750                        count++;
2751                    }
2752                }
2753                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2754            }, "prepareAppData");
2755
2756            // If this is first boot after an OTA, and a normal boot, then
2757            // we need to clear code cache directories.
2758            // Note that we do *not* clear the application profiles. These remain valid
2759            // across OTAs and are used to drive profile verification (post OTA) and
2760            // profile compilation (without waiting to collect a fresh set of profiles).
2761            if (mIsUpgrade && !onlyCore) {
2762                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2763                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2764                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2765                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2766                        // No apps are running this early, so no need to freeze
2767                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2768                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2769                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2770                    }
2771                }
2772                ver.fingerprint = Build.FINGERPRINT;
2773            }
2774
2775            checkDefaultBrowser();
2776
2777            // clear only after permissions and other defaults have been updated
2778            mExistingSystemPackages.clear();
2779            mPromoteSystemApps = false;
2780
2781            // All the changes are done during package scanning.
2782            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2783
2784            // can downgrade to reader
2785            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2786            mSettings.writeLPr();
2787            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2788
2789            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2790                    SystemClock.uptimeMillis());
2791
2792            if (!mOnlyCore) {
2793                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2794                mRequiredInstallerPackage = getRequiredInstallerLPr();
2795                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2796                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2797                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2798                        mIntentFilterVerifierComponent);
2799                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2800                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2801                        SharedLibraryInfo.VERSION_UNDEFINED);
2802                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2803                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2804                        SharedLibraryInfo.VERSION_UNDEFINED);
2805            } else {
2806                mRequiredVerifierPackage = null;
2807                mRequiredInstallerPackage = null;
2808                mRequiredUninstallerPackage = null;
2809                mIntentFilterVerifierComponent = null;
2810                mIntentFilterVerifier = null;
2811                mServicesSystemSharedLibraryPackageName = null;
2812                mSharedSystemSharedLibraryPackageName = null;
2813            }
2814
2815            mInstallerService = new PackageInstallerService(context, this);
2816            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2817            if (ephemeralResolverComponent != null) {
2818                if (DEBUG_EPHEMERAL) {
2819                    Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent);
2820                }
2821                mInstantAppResolverConnection =
2822                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2823                mInstantAppResolverSettingsComponent =
2824                        getEphemeralResolverSettingsLPr(ephemeralResolverComponent);
2825            } else {
2826                mInstantAppResolverConnection = null;
2827                mInstantAppResolverSettingsComponent = null;
2828            }
2829            updateInstantAppInstallerLocked();
2830
2831            // Read and update the usage of dex files.
2832            // Do this at the end of PM init so that all the packages have their
2833            // data directory reconciled.
2834            // At this point we know the code paths of the packages, so we can validate
2835            // the disk file and build the internal cache.
2836            // The usage file is expected to be small so loading and verifying it
2837            // should take a fairly small time compare to the other activities (e.g. package
2838            // scanning).
2839            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2840            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2841            for (int userId : currentUserIds) {
2842                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2843            }
2844            mDexManager.load(userPackages);
2845        } // synchronized (mPackages)
2846        } // synchronized (mInstallLock)
2847
2848        // Now after opening every single application zip, make sure they
2849        // are all flushed.  Not really needed, but keeps things nice and
2850        // tidy.
2851        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2852        Runtime.getRuntime().gc();
2853        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2854
2855        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2856        FallbackCategoryProvider.loadFallbacks();
2857        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2858
2859        // The initial scanning above does many calls into installd while
2860        // holding the mPackages lock, but we're mostly interested in yelling
2861        // once we have a booted system.
2862        mInstaller.setWarnIfHeld(mPackages);
2863
2864        // Expose private service for system components to use.
2865        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2866        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2867    }
2868
2869    private void updateInstantAppInstallerLocked() {
2870        final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent;
2871        final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr();
2872        ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null
2873                ? null : newInstantAppInstaller.getComponentName();
2874
2875        if (newInstantAppInstallerComponent != null
2876                && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) {
2877            if (DEBUG_EPHEMERAL) {
2878                Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent);
2879            }
2880            setUpInstantAppInstallerActivityLP(newInstantAppInstaller);
2881        } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) {
2882            Slog.d(TAG, "Unset ephemeral installer; none available");
2883        }
2884        mInstantAppInstallerComponent = newInstantAppInstallerComponent;
2885    }
2886
2887    private static File preparePackageParserCache(boolean isUpgrade) {
2888        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2889            return null;
2890        }
2891
2892        // Disable package parsing on eng builds to allow for faster incremental development.
2893        if ("eng".equals(Build.TYPE)) {
2894            return null;
2895        }
2896
2897        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2898            Slog.i(TAG, "Disabling package parser cache due to system property.");
2899            return null;
2900        }
2901
2902        // The base directory for the package parser cache lives under /data/system/.
2903        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2904                "package_cache");
2905        if (cacheBaseDir == null) {
2906            return null;
2907        }
2908
2909        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2910        // This also serves to "GC" unused entries when the package cache version changes (which
2911        // can only happen during upgrades).
2912        if (isUpgrade) {
2913            FileUtils.deleteContents(cacheBaseDir);
2914        }
2915
2916
2917        // Return the versioned package cache directory. This is something like
2918        // "/data/system/package_cache/1"
2919        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2920
2921        // The following is a workaround to aid development on non-numbered userdebug
2922        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2923        // the system partition is newer.
2924        //
2925        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2926        // that starts with "eng." to signify that this is an engineering build and not
2927        // destined for release.
2928        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2929            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2930
2931            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2932            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2933            // in general and should not be used for production changes. In this specific case,
2934            // we know that they will work.
2935            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2936            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2937                FileUtils.deleteContents(cacheBaseDir);
2938                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2939            }
2940        }
2941
2942        return cacheDir;
2943    }
2944
2945    @Override
2946    public boolean isFirstBoot() {
2947        return mFirstBoot;
2948    }
2949
2950    @Override
2951    public boolean isOnlyCoreApps() {
2952        return mOnlyCore;
2953    }
2954
2955    @Override
2956    public boolean isUpgrade() {
2957        return mIsUpgrade;
2958    }
2959
2960    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2961        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2962
2963        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2964                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2965                UserHandle.USER_SYSTEM);
2966        if (matches.size() == 1) {
2967            return matches.get(0).getComponentInfo().packageName;
2968        } else if (matches.size() == 0) {
2969            Log.e(TAG, "There should probably be a verifier, but, none were found");
2970            return null;
2971        }
2972        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2973    }
2974
2975    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2976        synchronized (mPackages) {
2977            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2978            if (libraryEntry == null) {
2979                throw new IllegalStateException("Missing required shared library:" + name);
2980            }
2981            return libraryEntry.apk;
2982        }
2983    }
2984
2985    private @NonNull String getRequiredInstallerLPr() {
2986        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2987        intent.addCategory(Intent.CATEGORY_DEFAULT);
2988        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2989
2990        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2991                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2992                UserHandle.USER_SYSTEM);
2993        if (matches.size() == 1) {
2994            ResolveInfo resolveInfo = matches.get(0);
2995            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2996                throw new RuntimeException("The installer must be a privileged app");
2997            }
2998            return matches.get(0).getComponentInfo().packageName;
2999        } else {
3000            throw new RuntimeException("There must be exactly one installer; found " + matches);
3001        }
3002    }
3003
3004    private @NonNull String getRequiredUninstallerLPr() {
3005        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3006        intent.addCategory(Intent.CATEGORY_DEFAULT);
3007        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3008
3009        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3010                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3011                UserHandle.USER_SYSTEM);
3012        if (resolveInfo == null ||
3013                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3014            throw new RuntimeException("There must be exactly one uninstaller; found "
3015                    + resolveInfo);
3016        }
3017        return resolveInfo.getComponentInfo().packageName;
3018    }
3019
3020    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3021        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3022
3023        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3024                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3025                UserHandle.USER_SYSTEM);
3026        ResolveInfo best = null;
3027        final int N = matches.size();
3028        for (int i = 0; i < N; i++) {
3029            final ResolveInfo cur = matches.get(i);
3030            final String packageName = cur.getComponentInfo().packageName;
3031            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3032                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3033                continue;
3034            }
3035
3036            if (best == null || cur.priority > best.priority) {
3037                best = cur;
3038            }
3039        }
3040
3041        if (best != null) {
3042            return best.getComponentInfo().getComponentName();
3043        } else {
3044            throw new RuntimeException("There must be at least one intent filter verifier");
3045        }
3046    }
3047
3048    private @Nullable ComponentName getEphemeralResolverLPr() {
3049        final String[] packageArray =
3050                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3051        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3052            if (DEBUG_EPHEMERAL) {
3053                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3054            }
3055            return null;
3056        }
3057
3058        final int callingUid = Binder.getCallingUid();
3059        final int resolveFlags =
3060                MATCH_DIRECT_BOOT_AWARE
3061                | MATCH_DIRECT_BOOT_UNAWARE
3062                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3063        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE);
3064        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3065                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3066        // temporarily look for the old action
3067        if (resolvers.size() == 0) {
3068            if (DEBUG_EPHEMERAL) {
3069                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3070            }
3071            resolverIntent.setAction(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3072            resolvers = queryIntentServicesInternal(resolverIntent, null,
3073                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3074        }
3075        final int N = resolvers.size();
3076        if (N == 0) {
3077            if (DEBUG_EPHEMERAL) {
3078                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3079            }
3080            return null;
3081        }
3082
3083        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3084        for (int i = 0; i < N; i++) {
3085            final ResolveInfo info = resolvers.get(i);
3086
3087            if (info.serviceInfo == null) {
3088                continue;
3089            }
3090
3091            final String packageName = info.serviceInfo.packageName;
3092            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3093                if (DEBUG_EPHEMERAL) {
3094                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3095                            + " pkg: " + packageName + ", info:" + info);
3096                }
3097                continue;
3098            }
3099
3100            if (DEBUG_EPHEMERAL) {
3101                Slog.v(TAG, "Ephemeral resolver found;"
3102                        + " pkg: " + packageName + ", info:" + info);
3103            }
3104            return new ComponentName(packageName, info.serviceInfo.name);
3105        }
3106        if (DEBUG_EPHEMERAL) {
3107            Slog.v(TAG, "Ephemeral resolver NOT found");
3108        }
3109        return null;
3110    }
3111
3112    private @Nullable ActivityInfo getEphemeralInstallerLPr() {
3113        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3114        intent.addCategory(Intent.CATEGORY_DEFAULT);
3115        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3116
3117        final int resolveFlags =
3118                MATCH_DIRECT_BOOT_AWARE
3119                | MATCH_DIRECT_BOOT_UNAWARE
3120                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3121        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3122                resolveFlags, UserHandle.USER_SYSTEM);
3123        // temporarily look for the old action
3124        if (matches.isEmpty()) {
3125            if (DEBUG_EPHEMERAL) {
3126                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3127            }
3128            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3129            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3130                    resolveFlags, UserHandle.USER_SYSTEM);
3131        }
3132        Iterator<ResolveInfo> iter = matches.iterator();
3133        while (iter.hasNext()) {
3134            final ResolveInfo rInfo = iter.next();
3135            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3136            if (ps != null) {
3137                final PermissionsState permissionsState = ps.getPermissionsState();
3138                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3139                    continue;
3140                }
3141            }
3142            iter.remove();
3143        }
3144        if (matches.size() == 0) {
3145            return null;
3146        } else if (matches.size() == 1) {
3147            return (ActivityInfo) matches.get(0).getComponentInfo();
3148        } else {
3149            throw new RuntimeException(
3150                    "There must be at most one ephemeral installer; found " + matches);
3151        }
3152    }
3153
3154    private @Nullable ComponentName getEphemeralResolverSettingsLPr(
3155            @NonNull ComponentName resolver) {
3156        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3157                .addCategory(Intent.CATEGORY_DEFAULT)
3158                .setPackage(resolver.getPackageName());
3159        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3160        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3161                UserHandle.USER_SYSTEM);
3162        // temporarily look for the old action
3163        if (matches.isEmpty()) {
3164            if (DEBUG_EPHEMERAL) {
3165                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3166            }
3167            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3168            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3169                    UserHandle.USER_SYSTEM);
3170        }
3171        if (matches.isEmpty()) {
3172            return null;
3173        }
3174        return matches.get(0).getComponentInfo().getComponentName();
3175    }
3176
3177    private void primeDomainVerificationsLPw(int userId) {
3178        if (DEBUG_DOMAIN_VERIFICATION) {
3179            Slog.d(TAG, "Priming domain verifications in user " + userId);
3180        }
3181
3182        SystemConfig systemConfig = SystemConfig.getInstance();
3183        ArraySet<String> packages = systemConfig.getLinkedApps();
3184
3185        for (String packageName : packages) {
3186            PackageParser.Package pkg = mPackages.get(packageName);
3187            if (pkg != null) {
3188                if (!pkg.isSystemApp()) {
3189                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3190                    continue;
3191                }
3192
3193                ArraySet<String> domains = null;
3194                for (PackageParser.Activity a : pkg.activities) {
3195                    for (ActivityIntentInfo filter : a.intents) {
3196                        if (hasValidDomains(filter)) {
3197                            if (domains == null) {
3198                                domains = new ArraySet<String>();
3199                            }
3200                            domains.addAll(filter.getHostsList());
3201                        }
3202                    }
3203                }
3204
3205                if (domains != null && domains.size() > 0) {
3206                    if (DEBUG_DOMAIN_VERIFICATION) {
3207                        Slog.v(TAG, "      + " + packageName);
3208                    }
3209                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3210                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3211                    // and then 'always' in the per-user state actually used for intent resolution.
3212                    final IntentFilterVerificationInfo ivi;
3213                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3214                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3215                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3216                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3217                } else {
3218                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3219                            + "' does not handle web links");
3220                }
3221            } else {
3222                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3223            }
3224        }
3225
3226        scheduleWritePackageRestrictionsLocked(userId);
3227        scheduleWriteSettingsLocked();
3228    }
3229
3230    private void applyFactoryDefaultBrowserLPw(int userId) {
3231        // The default browser app's package name is stored in a string resource,
3232        // with a product-specific overlay used for vendor customization.
3233        String browserPkg = mContext.getResources().getString(
3234                com.android.internal.R.string.default_browser);
3235        if (!TextUtils.isEmpty(browserPkg)) {
3236            // non-empty string => required to be a known package
3237            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3238            if (ps == null) {
3239                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3240                browserPkg = null;
3241            } else {
3242                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3243            }
3244        }
3245
3246        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3247        // default.  If there's more than one, just leave everything alone.
3248        if (browserPkg == null) {
3249            calculateDefaultBrowserLPw(userId);
3250        }
3251    }
3252
3253    private void calculateDefaultBrowserLPw(int userId) {
3254        List<String> allBrowsers = resolveAllBrowserApps(userId);
3255        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3256        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3257    }
3258
3259    private List<String> resolveAllBrowserApps(int userId) {
3260        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3261        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3262                PackageManager.MATCH_ALL, userId);
3263
3264        final int count = list.size();
3265        List<String> result = new ArrayList<String>(count);
3266        for (int i=0; i<count; i++) {
3267            ResolveInfo info = list.get(i);
3268            if (info.activityInfo == null
3269                    || !info.handleAllWebDataURI
3270                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3271                    || result.contains(info.activityInfo.packageName)) {
3272                continue;
3273            }
3274            result.add(info.activityInfo.packageName);
3275        }
3276
3277        return result;
3278    }
3279
3280    private boolean packageIsBrowser(String packageName, int userId) {
3281        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3282                PackageManager.MATCH_ALL, userId);
3283        final int N = list.size();
3284        for (int i = 0; i < N; i++) {
3285            ResolveInfo info = list.get(i);
3286            if (packageName.equals(info.activityInfo.packageName)) {
3287                return true;
3288            }
3289        }
3290        return false;
3291    }
3292
3293    private void checkDefaultBrowser() {
3294        final int myUserId = UserHandle.myUserId();
3295        final String packageName = getDefaultBrowserPackageName(myUserId);
3296        if (packageName != null) {
3297            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3298            if (info == null) {
3299                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3300                synchronized (mPackages) {
3301                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3302                }
3303            }
3304        }
3305    }
3306
3307    @Override
3308    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3309            throws RemoteException {
3310        try {
3311            return super.onTransact(code, data, reply, flags);
3312        } catch (RuntimeException e) {
3313            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3314                Slog.wtf(TAG, "Package Manager Crash", e);
3315            }
3316            throw e;
3317        }
3318    }
3319
3320    static int[] appendInts(int[] cur, int[] add) {
3321        if (add == null) return cur;
3322        if (cur == null) return add;
3323        final int N = add.length;
3324        for (int i=0; i<N; i++) {
3325            cur = appendInt(cur, add[i]);
3326        }
3327        return cur;
3328    }
3329
3330    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3331        if (!sUserManager.exists(userId)) return null;
3332        if (ps == null) {
3333            return null;
3334        }
3335        final PackageParser.Package p = ps.pkg;
3336        if (p == null) {
3337            return null;
3338        }
3339        // Filter out ephemeral app metadata:
3340        //   * The system/shell/root can see metadata for any app
3341        //   * An installed app can see metadata for 1) other installed apps
3342        //     and 2) ephemeral apps that have explicitly interacted with it
3343        //   * Ephemeral apps can only see their own data and exposed installed apps
3344        //   * Holding a signature permission allows seeing instant apps
3345        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3346        if (callingAppId != Process.SYSTEM_UID
3347                && callingAppId != Process.SHELL_UID
3348                && callingAppId != Process.ROOT_UID
3349                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3350                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3351            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3352            if (instantAppPackageName != null) {
3353                // ephemeral apps can only get information on themselves or
3354                // installed apps that are exposed.
3355                if (!instantAppPackageName.equals(p.packageName)
3356                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3357                    return null;
3358                }
3359            } else {
3360                if (ps.getInstantApp(userId)) {
3361                    // only get access to the ephemeral app if we've been granted access
3362                    if (!mInstantAppRegistry.isInstantAccessGranted(
3363                            userId, callingAppId, ps.appId)) {
3364                        return null;
3365                    }
3366                }
3367            }
3368        }
3369
3370        final PermissionsState permissionsState = ps.getPermissionsState();
3371
3372        // Compute GIDs only if requested
3373        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3374                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3375        // Compute granted permissions only if package has requested permissions
3376        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3377                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3378        final PackageUserState state = ps.readUserState(userId);
3379
3380        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3381                && ps.isSystem()) {
3382            flags |= MATCH_ANY_USER;
3383        }
3384
3385        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3386                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3387
3388        if (packageInfo == null) {
3389            return null;
3390        }
3391
3392        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3393
3394        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3395                resolveExternalPackageNameLPr(p);
3396
3397        return packageInfo;
3398    }
3399
3400    @Override
3401    public void checkPackageStartable(String packageName, int userId) {
3402        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3403
3404        synchronized (mPackages) {
3405            final PackageSetting ps = mSettings.mPackages.get(packageName);
3406            if (ps == null) {
3407                throw new SecurityException("Package " + packageName + " was not found!");
3408            }
3409
3410            if (!ps.getInstalled(userId)) {
3411                throw new SecurityException(
3412                        "Package " + packageName + " was not installed for user " + userId + "!");
3413            }
3414
3415            if (mSafeMode && !ps.isSystem()) {
3416                throw new SecurityException("Package " + packageName + " not a system app!");
3417            }
3418
3419            if (mFrozenPackages.contains(packageName)) {
3420                throw new SecurityException("Package " + packageName + " is currently frozen!");
3421            }
3422
3423            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3424                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3425                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3426            }
3427        }
3428    }
3429
3430    @Override
3431    public boolean isPackageAvailable(String packageName, int userId) {
3432        if (!sUserManager.exists(userId)) return false;
3433        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3434                false /* requireFullPermission */, false /* checkShell */, "is package available");
3435        synchronized (mPackages) {
3436            PackageParser.Package p = mPackages.get(packageName);
3437            if (p != null) {
3438                final PackageSetting ps = (PackageSetting) p.mExtras;
3439                if (ps != null) {
3440                    final PackageUserState state = ps.readUserState(userId);
3441                    if (state != null) {
3442                        return PackageParser.isAvailable(state);
3443                    }
3444                }
3445            }
3446        }
3447        return false;
3448    }
3449
3450    @Override
3451    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3452        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3453                flags, userId);
3454    }
3455
3456    @Override
3457    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3458            int flags, int userId) {
3459        return getPackageInfoInternal(versionedPackage.getPackageName(),
3460                // TODO: We will change version code to long, so in the new API it is long
3461                (int) versionedPackage.getVersionCode(), flags, userId);
3462    }
3463
3464    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3465            int flags, int userId) {
3466        if (!sUserManager.exists(userId)) return null;
3467        flags = updateFlagsForPackage(flags, userId, packageName);
3468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3469                false /* requireFullPermission */, false /* checkShell */, "get package info");
3470
3471        // reader
3472        synchronized (mPackages) {
3473            // Normalize package name to handle renamed packages and static libs
3474            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3475
3476            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3477            if (matchFactoryOnly) {
3478                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3479                if (ps != null) {
3480                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3481                        return null;
3482                    }
3483                    return generatePackageInfo(ps, flags, userId);
3484                }
3485            }
3486
3487            PackageParser.Package p = mPackages.get(packageName);
3488            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3489                return null;
3490            }
3491            if (DEBUG_PACKAGE_INFO)
3492                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3493            if (p != null) {
3494                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3495                        Binder.getCallingUid(), userId)) {
3496                    return null;
3497                }
3498                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3499            }
3500            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3501                final PackageSetting ps = mSettings.mPackages.get(packageName);
3502                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3503                    return null;
3504                }
3505                return generatePackageInfo(ps, flags, userId);
3506            }
3507        }
3508        return null;
3509    }
3510
3511
3512    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3513        // System/shell/root get to see all static libs
3514        final int appId = UserHandle.getAppId(uid);
3515        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3516                || appId == Process.ROOT_UID) {
3517            return false;
3518        }
3519
3520        // No package means no static lib as it is always on internal storage
3521        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3522            return false;
3523        }
3524
3525        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3526                ps.pkg.staticSharedLibVersion);
3527        if (libEntry == null) {
3528            return false;
3529        }
3530
3531        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3532        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3533        if (uidPackageNames == null) {
3534            return true;
3535        }
3536
3537        for (String uidPackageName : uidPackageNames) {
3538            if (ps.name.equals(uidPackageName)) {
3539                return false;
3540            }
3541            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3542            if (uidPs != null) {
3543                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3544                        libEntry.info.getName());
3545                if (index < 0) {
3546                    continue;
3547                }
3548                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3549                    return false;
3550                }
3551            }
3552        }
3553        return true;
3554    }
3555
3556    @Override
3557    public String[] currentToCanonicalPackageNames(String[] names) {
3558        String[] out = new String[names.length];
3559        // reader
3560        synchronized (mPackages) {
3561            for (int i=names.length-1; i>=0; i--) {
3562                PackageSetting ps = mSettings.mPackages.get(names[i]);
3563                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3564            }
3565        }
3566        return out;
3567    }
3568
3569    @Override
3570    public String[] canonicalToCurrentPackageNames(String[] names) {
3571        String[] out = new String[names.length];
3572        // reader
3573        synchronized (mPackages) {
3574            for (int i=names.length-1; i>=0; i--) {
3575                String cur = mSettings.getRenamedPackageLPr(names[i]);
3576                out[i] = cur != null ? cur : names[i];
3577            }
3578        }
3579        return out;
3580    }
3581
3582    @Override
3583    public int getPackageUid(String packageName, int flags, int userId) {
3584        if (!sUserManager.exists(userId)) return -1;
3585        flags = updateFlagsForPackage(flags, userId, packageName);
3586        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3587                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3588
3589        // reader
3590        synchronized (mPackages) {
3591            final PackageParser.Package p = mPackages.get(packageName);
3592            if (p != null && p.isMatch(flags)) {
3593                return UserHandle.getUid(userId, p.applicationInfo.uid);
3594            }
3595            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3596                final PackageSetting ps = mSettings.mPackages.get(packageName);
3597                if (ps != null && ps.isMatch(flags)) {
3598                    return UserHandle.getUid(userId, ps.appId);
3599                }
3600            }
3601        }
3602
3603        return -1;
3604    }
3605
3606    @Override
3607    public int[] getPackageGids(String packageName, int flags, int userId) {
3608        if (!sUserManager.exists(userId)) return null;
3609        flags = updateFlagsForPackage(flags, userId, packageName);
3610        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3611                false /* requireFullPermission */, false /* checkShell */,
3612                "getPackageGids");
3613
3614        // reader
3615        synchronized (mPackages) {
3616            final PackageParser.Package p = mPackages.get(packageName);
3617            if (p != null && p.isMatch(flags)) {
3618                PackageSetting ps = (PackageSetting) p.mExtras;
3619                // TODO: Shouldn't this be checking for package installed state for userId and
3620                // return null?
3621                return ps.getPermissionsState().computeGids(userId);
3622            }
3623            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3624                final PackageSetting ps = mSettings.mPackages.get(packageName);
3625                if (ps != null && ps.isMatch(flags)) {
3626                    return ps.getPermissionsState().computeGids(userId);
3627                }
3628            }
3629        }
3630
3631        return null;
3632    }
3633
3634    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3635        if (bp.perm != null) {
3636            return PackageParser.generatePermissionInfo(bp.perm, flags);
3637        }
3638        PermissionInfo pi = new PermissionInfo();
3639        pi.name = bp.name;
3640        pi.packageName = bp.sourcePackage;
3641        pi.nonLocalizedLabel = bp.name;
3642        pi.protectionLevel = bp.protectionLevel;
3643        return pi;
3644    }
3645
3646    @Override
3647    public PermissionInfo getPermissionInfo(String name, int flags) {
3648        // reader
3649        synchronized (mPackages) {
3650            final BasePermission p = mSettings.mPermissions.get(name);
3651            if (p != null) {
3652                return generatePermissionInfo(p, flags);
3653            }
3654            return null;
3655        }
3656    }
3657
3658    @Override
3659    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3660            int flags) {
3661        // reader
3662        synchronized (mPackages) {
3663            if (group != null && !mPermissionGroups.containsKey(group)) {
3664                // This is thrown as NameNotFoundException
3665                return null;
3666            }
3667
3668            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3669            for (BasePermission p : mSettings.mPermissions.values()) {
3670                if (group == null) {
3671                    if (p.perm == null || p.perm.info.group == null) {
3672                        out.add(generatePermissionInfo(p, flags));
3673                    }
3674                } else {
3675                    if (p.perm != null && group.equals(p.perm.info.group)) {
3676                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3677                    }
3678                }
3679            }
3680            return new ParceledListSlice<>(out);
3681        }
3682    }
3683
3684    @Override
3685    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3686        // reader
3687        synchronized (mPackages) {
3688            return PackageParser.generatePermissionGroupInfo(
3689                    mPermissionGroups.get(name), flags);
3690        }
3691    }
3692
3693    @Override
3694    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3695        // reader
3696        synchronized (mPackages) {
3697            final int N = mPermissionGroups.size();
3698            ArrayList<PermissionGroupInfo> out
3699                    = new ArrayList<PermissionGroupInfo>(N);
3700            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3701                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3702            }
3703            return new ParceledListSlice<>(out);
3704        }
3705    }
3706
3707    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3708            int uid, int userId) {
3709        if (!sUserManager.exists(userId)) return null;
3710        PackageSetting ps = mSettings.mPackages.get(packageName);
3711        if (ps != null) {
3712            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3713                return null;
3714            }
3715            if (ps.pkg == null) {
3716                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3717                if (pInfo != null) {
3718                    return pInfo.applicationInfo;
3719                }
3720                return null;
3721            }
3722            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3723                    ps.readUserState(userId), userId);
3724            if (ai != null) {
3725                rebaseEnabledOverlays(ai, userId);
3726                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3727            }
3728            return ai;
3729        }
3730        return null;
3731    }
3732
3733    @Override
3734    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3735        if (!sUserManager.exists(userId)) return null;
3736        flags = updateFlagsForApplication(flags, userId, packageName);
3737        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3738                false /* requireFullPermission */, false /* checkShell */, "get application info");
3739
3740        // writer
3741        synchronized (mPackages) {
3742            // Normalize package name to handle renamed packages and static libs
3743            packageName = resolveInternalPackageNameLPr(packageName,
3744                    PackageManager.VERSION_CODE_HIGHEST);
3745
3746            PackageParser.Package p = mPackages.get(packageName);
3747            if (DEBUG_PACKAGE_INFO) Log.v(
3748                    TAG, "getApplicationInfo " + packageName
3749                    + ": " + p);
3750            if (p != null) {
3751                PackageSetting ps = mSettings.mPackages.get(packageName);
3752                if (ps == null) return null;
3753                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3754                    return null;
3755                }
3756                // Note: isEnabledLP() does not apply here - always return info
3757                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3758                        p, flags, ps.readUserState(userId), userId);
3759                if (ai != null) {
3760                    rebaseEnabledOverlays(ai, userId);
3761                    ai.packageName = resolveExternalPackageNameLPr(p);
3762                }
3763                return ai;
3764            }
3765            if ("android".equals(packageName)||"system".equals(packageName)) {
3766                return mAndroidApplication;
3767            }
3768            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3769                // Already generates the external package name
3770                return generateApplicationInfoFromSettingsLPw(packageName,
3771                        Binder.getCallingUid(), flags, userId);
3772            }
3773        }
3774        return null;
3775    }
3776
3777    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3778        List<String> paths = new ArrayList<>();
3779        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3780            mEnabledOverlayPaths.get(userId);
3781        if (userSpecificOverlays != null) {
3782            if (!"android".equals(ai.packageName)) {
3783                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3784                if (frameworkOverlays != null) {
3785                    paths.addAll(frameworkOverlays);
3786                }
3787            }
3788
3789            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3790            if (appOverlays != null) {
3791                paths.addAll(appOverlays);
3792            }
3793        }
3794        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3795    }
3796
3797    private String normalizePackageNameLPr(String packageName) {
3798        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3799        return normalizedPackageName != null ? normalizedPackageName : packageName;
3800    }
3801
3802    @Override
3803    public void deletePreloadsFileCache() {
3804        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3805            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3806        }
3807        File dir = Environment.getDataPreloadsFileCacheDirectory();
3808        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3809        FileUtils.deleteContents(dir);
3810    }
3811
3812    @Override
3813    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3814            final IPackageDataObserver observer) {
3815        mContext.enforceCallingOrSelfPermission(
3816                android.Manifest.permission.CLEAR_APP_CACHE, null);
3817        mHandler.post(() -> {
3818            boolean success = false;
3819            try {
3820                freeStorage(volumeUuid, freeStorageSize, 0);
3821                success = true;
3822            } catch (IOException e) {
3823                Slog.w(TAG, e);
3824            }
3825            if (observer != null) {
3826                try {
3827                    observer.onRemoveCompleted(null, success);
3828                } catch (RemoteException e) {
3829                    Slog.w(TAG, e);
3830                }
3831            }
3832        });
3833    }
3834
3835    @Override
3836    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3837            final IntentSender pi) {
3838        mContext.enforceCallingOrSelfPermission(
3839                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3840        mHandler.post(() -> {
3841            boolean success = false;
3842            try {
3843                freeStorage(volumeUuid, freeStorageSize, 0);
3844                success = true;
3845            } catch (IOException e) {
3846                Slog.w(TAG, e);
3847            }
3848            if (pi != null) {
3849                try {
3850                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3851                } catch (SendIntentException e) {
3852                    Slog.w(TAG, e);
3853                }
3854            }
3855        });
3856    }
3857
3858    /**
3859     * Blocking call to clear various types of cached data across the system
3860     * until the requested bytes are available.
3861     */
3862    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3863        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3864        final File file = storage.findPathForUuid(volumeUuid);
3865        if (file.getUsableSpace() >= bytes) return;
3866
3867        if (ENABLE_FREE_CACHE_V2) {
3868            final boolean aggressive = (storageFlags
3869                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3870            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3871                    volumeUuid);
3872
3873            // 1. Pre-flight to determine if we have any chance to succeed
3874            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3875            if (internalVolume && (aggressive || SystemProperties
3876                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3877                deletePreloadsFileCache();
3878                if (file.getUsableSpace() >= bytes) return;
3879            }
3880
3881            // 3. Consider parsed APK data (aggressive only)
3882            if (internalVolume && aggressive) {
3883                FileUtils.deleteContents(mCacheDir);
3884                if (file.getUsableSpace() >= bytes) return;
3885            }
3886
3887            // 4. Consider cached app data (above quotas)
3888            try {
3889                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3890            } catch (InstallerException ignored) {
3891            }
3892            if (file.getUsableSpace() >= bytes) return;
3893
3894            // 5. Consider shared libraries with refcount=0 and age>2h
3895            // 6. Consider dexopt output (aggressive only)
3896            // 7. Consider ephemeral apps not used in last week
3897
3898            // 8. Consider cached app data (below quotas)
3899            try {
3900                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3901                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3902            } catch (InstallerException ignored) {
3903            }
3904            if (file.getUsableSpace() >= bytes) return;
3905
3906            // 9. Consider DropBox entries
3907            // 10. Consider ephemeral cookies
3908
3909        } else {
3910            try {
3911                mInstaller.freeCache(volumeUuid, bytes, 0);
3912            } catch (InstallerException ignored) {
3913            }
3914            if (file.getUsableSpace() >= bytes) return;
3915        }
3916
3917        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3918    }
3919
3920    /**
3921     * Update given flags based on encryption status of current user.
3922     */
3923    private int updateFlags(int flags, int userId) {
3924        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3925                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3926            // Caller expressed an explicit opinion about what encryption
3927            // aware/unaware components they want to see, so fall through and
3928            // give them what they want
3929        } else {
3930            // Caller expressed no opinion, so match based on user state
3931            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3932                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3933            } else {
3934                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3935            }
3936        }
3937        return flags;
3938    }
3939
3940    private UserManagerInternal getUserManagerInternal() {
3941        if (mUserManagerInternal == null) {
3942            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3943        }
3944        return mUserManagerInternal;
3945    }
3946
3947    private DeviceIdleController.LocalService getDeviceIdleController() {
3948        if (mDeviceIdleController == null) {
3949            mDeviceIdleController =
3950                    LocalServices.getService(DeviceIdleController.LocalService.class);
3951        }
3952        return mDeviceIdleController;
3953    }
3954
3955    /**
3956     * Update given flags when being used to request {@link PackageInfo}.
3957     */
3958    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3959        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3960        boolean triaged = true;
3961        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3962                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3963            // Caller is asking for component details, so they'd better be
3964            // asking for specific encryption matching behavior, or be triaged
3965            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3966                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3967                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3968                triaged = false;
3969            }
3970        }
3971        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3972                | PackageManager.MATCH_SYSTEM_ONLY
3973                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3974            triaged = false;
3975        }
3976        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3977            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3978                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3979                    + Debug.getCallers(5));
3980        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3981                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3982            // If the caller wants all packages and has a restricted profile associated with it,
3983            // then match all users. This is to make sure that launchers that need to access work
3984            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3985            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3986            flags |= PackageManager.MATCH_ANY_USER;
3987        }
3988        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3989            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3990                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3991        }
3992        return updateFlags(flags, userId);
3993    }
3994
3995    /**
3996     * Update given flags when being used to request {@link ApplicationInfo}.
3997     */
3998    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3999        return updateFlagsForPackage(flags, userId, cookie);
4000    }
4001
4002    /**
4003     * Update given flags when being used to request {@link ComponentInfo}.
4004     */
4005    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4006        if (cookie instanceof Intent) {
4007            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4008                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4009            }
4010        }
4011
4012        boolean triaged = true;
4013        // Caller is asking for component details, so they'd better be
4014        // asking for specific encryption matching behavior, or be triaged
4015        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4016                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4017                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4018            triaged = false;
4019        }
4020        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4021            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4022                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4023        }
4024
4025        return updateFlags(flags, userId);
4026    }
4027
4028    /**
4029     * Update given intent when being used to request {@link ResolveInfo}.
4030     */
4031    private Intent updateIntentForResolve(Intent intent) {
4032        if (intent.getSelector() != null) {
4033            intent = intent.getSelector();
4034        }
4035        if (DEBUG_PREFERRED) {
4036            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4037        }
4038        return intent;
4039    }
4040
4041    /**
4042     * Update given flags when being used to request {@link ResolveInfo}.
4043     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4044     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4045     * flag set. However, this flag is only honoured in three circumstances:
4046     * <ul>
4047     * <li>when called from a system process</li>
4048     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4049     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4050     * action and a {@code android.intent.category.BROWSABLE} category</li>
4051     * </ul>
4052     */
4053    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4054            boolean includeInstantApps) {
4055        // Safe mode means we shouldn't match any third-party components
4056        if (mSafeMode) {
4057            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4058        }
4059        if (getInstantAppPackageName(callingUid) != null) {
4060            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4061            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4062            flags |= PackageManager.MATCH_INSTANT;
4063        } else {
4064            // Otherwise, prevent leaking ephemeral components
4065            final boolean isSpecialProcess =
4066                    callingUid == Process.SYSTEM_UID
4067                    || callingUid == Process.SHELL_UID
4068                    || callingUid == 0;
4069            final boolean allowMatchInstant =
4070                    (includeInstantApps
4071                            && Intent.ACTION_VIEW.equals(intent.getAction())
4072                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4073                            && hasWebURI(intent))
4074                    || isSpecialProcess
4075                    || mContext.checkCallingOrSelfPermission(
4076                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4077            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4078            if (!allowMatchInstant) {
4079                flags &= ~PackageManager.MATCH_INSTANT;
4080            }
4081        }
4082        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4083    }
4084
4085    @Override
4086    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4087        if (!sUserManager.exists(userId)) return null;
4088        flags = updateFlagsForComponent(flags, userId, component);
4089        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4090                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4091        synchronized (mPackages) {
4092            PackageParser.Activity a = mActivities.mActivities.get(component);
4093
4094            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4095            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4096                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4097                if (ps == null) return null;
4098                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4099                        userId);
4100            }
4101            if (mResolveComponentName.equals(component)) {
4102                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4103                        new PackageUserState(), userId);
4104            }
4105        }
4106        return null;
4107    }
4108
4109    @Override
4110    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4111            String resolvedType) {
4112        synchronized (mPackages) {
4113            if (component.equals(mResolveComponentName)) {
4114                // The resolver supports EVERYTHING!
4115                return true;
4116            }
4117            PackageParser.Activity a = mActivities.mActivities.get(component);
4118            if (a == null) {
4119                return false;
4120            }
4121            for (int i=0; i<a.intents.size(); i++) {
4122                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4123                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4124                    return true;
4125                }
4126            }
4127            return false;
4128        }
4129    }
4130
4131    @Override
4132    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4133        if (!sUserManager.exists(userId)) return null;
4134        flags = updateFlagsForComponent(flags, userId, component);
4135        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4136                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4137        synchronized (mPackages) {
4138            PackageParser.Activity a = mReceivers.mActivities.get(component);
4139            if (DEBUG_PACKAGE_INFO) Log.v(
4140                TAG, "getReceiverInfo " + component + ": " + a);
4141            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4142                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4143                if (ps == null) return null;
4144                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4145                        ps.readUserState(userId), userId);
4146                if (ri != null) {
4147                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4148                }
4149                return ri;
4150            }
4151        }
4152        return null;
4153    }
4154
4155    @Override
4156    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4157        if (!sUserManager.exists(userId)) return null;
4158        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4159
4160        flags = updateFlagsForPackage(flags, userId, null);
4161
4162        final boolean canSeeStaticLibraries =
4163                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4164                        == PERMISSION_GRANTED
4165                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4166                        == PERMISSION_GRANTED
4167                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4168                        == PERMISSION_GRANTED
4169                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4170                        == PERMISSION_GRANTED;
4171
4172        synchronized (mPackages) {
4173            List<SharedLibraryInfo> result = null;
4174
4175            final int libCount = mSharedLibraries.size();
4176            for (int i = 0; i < libCount; i++) {
4177                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4178                if (versionedLib == null) {
4179                    continue;
4180                }
4181
4182                final int versionCount = versionedLib.size();
4183                for (int j = 0; j < versionCount; j++) {
4184                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4185                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4186                        break;
4187                    }
4188                    final long identity = Binder.clearCallingIdentity();
4189                    try {
4190                        // TODO: We will change version code to long, so in the new API it is long
4191                        PackageInfo packageInfo = getPackageInfoVersioned(
4192                                libInfo.getDeclaringPackage(), flags, userId);
4193                        if (packageInfo == null) {
4194                            continue;
4195                        }
4196                    } finally {
4197                        Binder.restoreCallingIdentity(identity);
4198                    }
4199
4200                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4201                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4202                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4203
4204                    if (result == null) {
4205                        result = new ArrayList<>();
4206                    }
4207                    result.add(resLibInfo);
4208                }
4209            }
4210
4211            return result != null ? new ParceledListSlice<>(result) : null;
4212        }
4213    }
4214
4215    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4216            SharedLibraryInfo libInfo, int flags, int userId) {
4217        List<VersionedPackage> versionedPackages = null;
4218        final int packageCount = mSettings.mPackages.size();
4219        for (int i = 0; i < packageCount; i++) {
4220            PackageSetting ps = mSettings.mPackages.valueAt(i);
4221
4222            if (ps == null) {
4223                continue;
4224            }
4225
4226            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4227                continue;
4228            }
4229
4230            final String libName = libInfo.getName();
4231            if (libInfo.isStatic()) {
4232                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4233                if (libIdx < 0) {
4234                    continue;
4235                }
4236                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4237                    continue;
4238                }
4239                if (versionedPackages == null) {
4240                    versionedPackages = new ArrayList<>();
4241                }
4242                // If the dependent is a static shared lib, use the public package name
4243                String dependentPackageName = ps.name;
4244                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4245                    dependentPackageName = ps.pkg.manifestPackageName;
4246                }
4247                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4248            } else if (ps.pkg != null) {
4249                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4250                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4251                    if (versionedPackages == null) {
4252                        versionedPackages = new ArrayList<>();
4253                    }
4254                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4255                }
4256            }
4257        }
4258
4259        return versionedPackages;
4260    }
4261
4262    @Override
4263    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4264        if (!sUserManager.exists(userId)) return null;
4265        flags = updateFlagsForComponent(flags, userId, component);
4266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4267                false /* requireFullPermission */, false /* checkShell */, "get service info");
4268        synchronized (mPackages) {
4269            PackageParser.Service s = mServices.mServices.get(component);
4270            if (DEBUG_PACKAGE_INFO) Log.v(
4271                TAG, "getServiceInfo " + component + ": " + s);
4272            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4273                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4274                if (ps == null) return null;
4275                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4276                        ps.readUserState(userId), userId);
4277                if (si != null) {
4278                    rebaseEnabledOverlays(si.applicationInfo, userId);
4279                }
4280                return si;
4281            }
4282        }
4283        return null;
4284    }
4285
4286    @Override
4287    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4288        if (!sUserManager.exists(userId)) return null;
4289        flags = updateFlagsForComponent(flags, userId, component);
4290        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4291                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4292        synchronized (mPackages) {
4293            PackageParser.Provider p = mProviders.mProviders.get(component);
4294            if (DEBUG_PACKAGE_INFO) Log.v(
4295                TAG, "getProviderInfo " + component + ": " + p);
4296            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4297                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4298                if (ps == null) return null;
4299                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4300                        ps.readUserState(userId), userId);
4301                if (pi != null) {
4302                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4303                }
4304                return pi;
4305            }
4306        }
4307        return null;
4308    }
4309
4310    @Override
4311    public String[] getSystemSharedLibraryNames() {
4312        synchronized (mPackages) {
4313            Set<String> libs = null;
4314            final int libCount = mSharedLibraries.size();
4315            for (int i = 0; i < libCount; i++) {
4316                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4317                if (versionedLib == null) {
4318                    continue;
4319                }
4320                final int versionCount = versionedLib.size();
4321                for (int j = 0; j < versionCount; j++) {
4322                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4323                    if (!libEntry.info.isStatic()) {
4324                        if (libs == null) {
4325                            libs = new ArraySet<>();
4326                        }
4327                        libs.add(libEntry.info.getName());
4328                        break;
4329                    }
4330                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4331                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4332                            UserHandle.getUserId(Binder.getCallingUid()))) {
4333                        if (libs == null) {
4334                            libs = new ArraySet<>();
4335                        }
4336                        libs.add(libEntry.info.getName());
4337                        break;
4338                    }
4339                }
4340            }
4341
4342            if (libs != null) {
4343                String[] libsArray = new String[libs.size()];
4344                libs.toArray(libsArray);
4345                return libsArray;
4346            }
4347
4348            return null;
4349        }
4350    }
4351
4352    @Override
4353    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4354        synchronized (mPackages) {
4355            return mServicesSystemSharedLibraryPackageName;
4356        }
4357    }
4358
4359    @Override
4360    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4361        synchronized (mPackages) {
4362            return mSharedSystemSharedLibraryPackageName;
4363        }
4364    }
4365
4366    private void updateSequenceNumberLP(String packageName, int[] userList) {
4367        for (int i = userList.length - 1; i >= 0; --i) {
4368            final int userId = userList[i];
4369            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4370            if (changedPackages == null) {
4371                changedPackages = new SparseArray<>();
4372                mChangedPackages.put(userId, changedPackages);
4373            }
4374            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4375            if (sequenceNumbers == null) {
4376                sequenceNumbers = new HashMap<>();
4377                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4378            }
4379            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4380            if (sequenceNumber != null) {
4381                changedPackages.remove(sequenceNumber);
4382            }
4383            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4384            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4385        }
4386        mChangedPackagesSequenceNumber++;
4387    }
4388
4389    @Override
4390    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4391        synchronized (mPackages) {
4392            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4393                return null;
4394            }
4395            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4396            if (changedPackages == null) {
4397                return null;
4398            }
4399            final List<String> packageNames =
4400                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4401            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4402                final String packageName = changedPackages.get(i);
4403                if (packageName != null) {
4404                    packageNames.add(packageName);
4405                }
4406            }
4407            return packageNames.isEmpty()
4408                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4409        }
4410    }
4411
4412    @Override
4413    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4414        ArrayList<FeatureInfo> res;
4415        synchronized (mAvailableFeatures) {
4416            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4417            res.addAll(mAvailableFeatures.values());
4418        }
4419        final FeatureInfo fi = new FeatureInfo();
4420        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4421                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4422        res.add(fi);
4423
4424        return new ParceledListSlice<>(res);
4425    }
4426
4427    @Override
4428    public boolean hasSystemFeature(String name, int version) {
4429        synchronized (mAvailableFeatures) {
4430            final FeatureInfo feat = mAvailableFeatures.get(name);
4431            if (feat == null) {
4432                return false;
4433            } else {
4434                return feat.version >= version;
4435            }
4436        }
4437    }
4438
4439    @Override
4440    public int checkPermission(String permName, String pkgName, int userId) {
4441        if (!sUserManager.exists(userId)) {
4442            return PackageManager.PERMISSION_DENIED;
4443        }
4444
4445        synchronized (mPackages) {
4446            final PackageParser.Package p = mPackages.get(pkgName);
4447            if (p != null && p.mExtras != null) {
4448                final PackageSetting ps = (PackageSetting) p.mExtras;
4449                final PermissionsState permissionsState = ps.getPermissionsState();
4450                if (permissionsState.hasPermission(permName, userId)) {
4451                    return PackageManager.PERMISSION_GRANTED;
4452                }
4453                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4454                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4455                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4456                    return PackageManager.PERMISSION_GRANTED;
4457                }
4458            }
4459        }
4460
4461        return PackageManager.PERMISSION_DENIED;
4462    }
4463
4464    @Override
4465    public int checkUidPermission(String permName, int uid) {
4466        final int userId = UserHandle.getUserId(uid);
4467
4468        if (!sUserManager.exists(userId)) {
4469            return PackageManager.PERMISSION_DENIED;
4470        }
4471
4472        synchronized (mPackages) {
4473            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4474            if (obj != null) {
4475                final SettingBase ps = (SettingBase) obj;
4476                final PermissionsState permissionsState = ps.getPermissionsState();
4477                if (permissionsState.hasPermission(permName, userId)) {
4478                    return PackageManager.PERMISSION_GRANTED;
4479                }
4480                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4481                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4482                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4483                    return PackageManager.PERMISSION_GRANTED;
4484                }
4485            } else {
4486                ArraySet<String> perms = mSystemPermissions.get(uid);
4487                if (perms != null) {
4488                    if (perms.contains(permName)) {
4489                        return PackageManager.PERMISSION_GRANTED;
4490                    }
4491                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4492                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4493                        return PackageManager.PERMISSION_GRANTED;
4494                    }
4495                }
4496            }
4497        }
4498
4499        return PackageManager.PERMISSION_DENIED;
4500    }
4501
4502    @Override
4503    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4504        if (UserHandle.getCallingUserId() != userId) {
4505            mContext.enforceCallingPermission(
4506                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4507                    "isPermissionRevokedByPolicy for user " + userId);
4508        }
4509
4510        if (checkPermission(permission, packageName, userId)
4511                == PackageManager.PERMISSION_GRANTED) {
4512            return false;
4513        }
4514
4515        final long identity = Binder.clearCallingIdentity();
4516        try {
4517            final int flags = getPermissionFlags(permission, packageName, userId);
4518            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4519        } finally {
4520            Binder.restoreCallingIdentity(identity);
4521        }
4522    }
4523
4524    @Override
4525    public String getPermissionControllerPackageName() {
4526        synchronized (mPackages) {
4527            return mRequiredInstallerPackage;
4528        }
4529    }
4530
4531    /**
4532     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4533     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4534     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4535     * @param message the message to log on security exception
4536     */
4537    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4538            boolean checkShell, String message) {
4539        if (userId < 0) {
4540            throw new IllegalArgumentException("Invalid userId " + userId);
4541        }
4542        if (checkShell) {
4543            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4544        }
4545        if (userId == UserHandle.getUserId(callingUid)) return;
4546        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4547            if (requireFullPermission) {
4548                mContext.enforceCallingOrSelfPermission(
4549                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4550            } else {
4551                try {
4552                    mContext.enforceCallingOrSelfPermission(
4553                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4554                } catch (SecurityException se) {
4555                    mContext.enforceCallingOrSelfPermission(
4556                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4557                }
4558            }
4559        }
4560    }
4561
4562    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4563        if (callingUid == Process.SHELL_UID) {
4564            if (userHandle >= 0
4565                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4566                throw new SecurityException("Shell does not have permission to access user "
4567                        + userHandle);
4568            } else if (userHandle < 0) {
4569                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4570                        + Debug.getCallers(3));
4571            }
4572        }
4573    }
4574
4575    private BasePermission findPermissionTreeLP(String permName) {
4576        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4577            if (permName.startsWith(bp.name) &&
4578                    permName.length() > bp.name.length() &&
4579                    permName.charAt(bp.name.length()) == '.') {
4580                return bp;
4581            }
4582        }
4583        return null;
4584    }
4585
4586    private BasePermission checkPermissionTreeLP(String permName) {
4587        if (permName != null) {
4588            BasePermission bp = findPermissionTreeLP(permName);
4589            if (bp != null) {
4590                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4591                    return bp;
4592                }
4593                throw new SecurityException("Calling uid "
4594                        + Binder.getCallingUid()
4595                        + " is not allowed to add to permission tree "
4596                        + bp.name + " owned by uid " + bp.uid);
4597            }
4598        }
4599        throw new SecurityException("No permission tree found for " + permName);
4600    }
4601
4602    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4603        if (s1 == null) {
4604            return s2 == null;
4605        }
4606        if (s2 == null) {
4607            return false;
4608        }
4609        if (s1.getClass() != s2.getClass()) {
4610            return false;
4611        }
4612        return s1.equals(s2);
4613    }
4614
4615    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4616        if (pi1.icon != pi2.icon) return false;
4617        if (pi1.logo != pi2.logo) return false;
4618        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4619        if (!compareStrings(pi1.name, pi2.name)) return false;
4620        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4621        // We'll take care of setting this one.
4622        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4623        // These are not currently stored in settings.
4624        //if (!compareStrings(pi1.group, pi2.group)) return false;
4625        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4626        //if (pi1.labelRes != pi2.labelRes) return false;
4627        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4628        return true;
4629    }
4630
4631    int permissionInfoFootprint(PermissionInfo info) {
4632        int size = info.name.length();
4633        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4634        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4635        return size;
4636    }
4637
4638    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4639        int size = 0;
4640        for (BasePermission perm : mSettings.mPermissions.values()) {
4641            if (perm.uid == tree.uid) {
4642                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4643            }
4644        }
4645        return size;
4646    }
4647
4648    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4649        // We calculate the max size of permissions defined by this uid and throw
4650        // if that plus the size of 'info' would exceed our stated maximum.
4651        if (tree.uid != Process.SYSTEM_UID) {
4652            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4653            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4654                throw new SecurityException("Permission tree size cap exceeded");
4655            }
4656        }
4657    }
4658
4659    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4660        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4661            throw new SecurityException("Label must be specified in permission");
4662        }
4663        BasePermission tree = checkPermissionTreeLP(info.name);
4664        BasePermission bp = mSettings.mPermissions.get(info.name);
4665        boolean added = bp == null;
4666        boolean changed = true;
4667        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4668        if (added) {
4669            enforcePermissionCapLocked(info, tree);
4670            bp = new BasePermission(info.name, tree.sourcePackage,
4671                    BasePermission.TYPE_DYNAMIC);
4672        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4673            throw new SecurityException(
4674                    "Not allowed to modify non-dynamic permission "
4675                    + info.name);
4676        } else {
4677            if (bp.protectionLevel == fixedLevel
4678                    && bp.perm.owner.equals(tree.perm.owner)
4679                    && bp.uid == tree.uid
4680                    && comparePermissionInfos(bp.perm.info, info)) {
4681                changed = false;
4682            }
4683        }
4684        bp.protectionLevel = fixedLevel;
4685        info = new PermissionInfo(info);
4686        info.protectionLevel = fixedLevel;
4687        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4688        bp.perm.info.packageName = tree.perm.info.packageName;
4689        bp.uid = tree.uid;
4690        if (added) {
4691            mSettings.mPermissions.put(info.name, bp);
4692        }
4693        if (changed) {
4694            if (!async) {
4695                mSettings.writeLPr();
4696            } else {
4697                scheduleWriteSettingsLocked();
4698            }
4699        }
4700        return added;
4701    }
4702
4703    @Override
4704    public boolean addPermission(PermissionInfo info) {
4705        synchronized (mPackages) {
4706            return addPermissionLocked(info, false);
4707        }
4708    }
4709
4710    @Override
4711    public boolean addPermissionAsync(PermissionInfo info) {
4712        synchronized (mPackages) {
4713            return addPermissionLocked(info, true);
4714        }
4715    }
4716
4717    @Override
4718    public void removePermission(String name) {
4719        synchronized (mPackages) {
4720            checkPermissionTreeLP(name);
4721            BasePermission bp = mSettings.mPermissions.get(name);
4722            if (bp != null) {
4723                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4724                    throw new SecurityException(
4725                            "Not allowed to modify non-dynamic permission "
4726                            + name);
4727                }
4728                mSettings.mPermissions.remove(name);
4729                mSettings.writeLPr();
4730            }
4731        }
4732    }
4733
4734    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4735            BasePermission bp) {
4736        int index = pkg.requestedPermissions.indexOf(bp.name);
4737        if (index == -1) {
4738            throw new SecurityException("Package " + pkg.packageName
4739                    + " has not requested permission " + bp.name);
4740        }
4741        if (!bp.isRuntime() && !bp.isDevelopment()) {
4742            throw new SecurityException("Permission " + bp.name
4743                    + " is not a changeable permission type");
4744        }
4745    }
4746
4747    @Override
4748    public void grantRuntimePermission(String packageName, String name, final int userId) {
4749        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4750    }
4751
4752    private void grantRuntimePermission(String packageName, String name, final int userId,
4753            boolean overridePolicy) {
4754        if (!sUserManager.exists(userId)) {
4755            Log.e(TAG, "No such user:" + userId);
4756            return;
4757        }
4758
4759        mContext.enforceCallingOrSelfPermission(
4760                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4761                "grantRuntimePermission");
4762
4763        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4764                true /* requireFullPermission */, true /* checkShell */,
4765                "grantRuntimePermission");
4766
4767        final int uid;
4768        final SettingBase sb;
4769
4770        synchronized (mPackages) {
4771            final PackageParser.Package pkg = mPackages.get(packageName);
4772            if (pkg == null) {
4773                throw new IllegalArgumentException("Unknown package: " + packageName);
4774            }
4775
4776            final BasePermission bp = mSettings.mPermissions.get(name);
4777            if (bp == null) {
4778                throw new IllegalArgumentException("Unknown permission: " + name);
4779            }
4780
4781            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4782
4783            // If a permission review is required for legacy apps we represent
4784            // their permissions as always granted runtime ones since we need
4785            // to keep the review required permission flag per user while an
4786            // install permission's state is shared across all users.
4787            if (mPermissionReviewRequired
4788                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4789                    && bp.isRuntime()) {
4790                return;
4791            }
4792
4793            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4794            sb = (SettingBase) pkg.mExtras;
4795            if (sb == null) {
4796                throw new IllegalArgumentException("Unknown package: " + packageName);
4797            }
4798
4799            final PermissionsState permissionsState = sb.getPermissionsState();
4800
4801            final int flags = permissionsState.getPermissionFlags(name, userId);
4802            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4803                throw new SecurityException("Cannot grant system fixed permission "
4804                        + name + " for package " + packageName);
4805            }
4806            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4807                throw new SecurityException("Cannot grant policy fixed permission "
4808                        + name + " for package " + packageName);
4809            }
4810
4811            if (bp.isDevelopment()) {
4812                // Development permissions must be handled specially, since they are not
4813                // normal runtime permissions.  For now they apply to all users.
4814                if (permissionsState.grantInstallPermission(bp) !=
4815                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4816                    scheduleWriteSettingsLocked();
4817                }
4818                return;
4819            }
4820
4821            final PackageSetting ps = mSettings.mPackages.get(packageName);
4822            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4823                throw new SecurityException("Cannot grant non-ephemeral permission"
4824                        + name + " for package " + packageName);
4825            }
4826
4827            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4828                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4829                return;
4830            }
4831
4832            final int result = permissionsState.grantRuntimePermission(bp, userId);
4833            switch (result) {
4834                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4835                    return;
4836                }
4837
4838                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4839                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4840                    mHandler.post(new Runnable() {
4841                        @Override
4842                        public void run() {
4843                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4844                        }
4845                    });
4846                }
4847                break;
4848            }
4849
4850            if (bp.isRuntime()) {
4851                logPermissionGranted(mContext, name, packageName);
4852            }
4853
4854            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4855
4856            // Not critical if that is lost - app has to request again.
4857            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4858        }
4859
4860        // Only need to do this if user is initialized. Otherwise it's a new user
4861        // and there are no processes running as the user yet and there's no need
4862        // to make an expensive call to remount processes for the changed permissions.
4863        if (READ_EXTERNAL_STORAGE.equals(name)
4864                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4865            final long token = Binder.clearCallingIdentity();
4866            try {
4867                if (sUserManager.isInitialized(userId)) {
4868                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4869                            StorageManagerInternal.class);
4870                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4871                }
4872            } finally {
4873                Binder.restoreCallingIdentity(token);
4874            }
4875        }
4876    }
4877
4878    @Override
4879    public void revokeRuntimePermission(String packageName, String name, int userId) {
4880        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4881    }
4882
4883    private void revokeRuntimePermission(String packageName, String name, int userId,
4884            boolean overridePolicy) {
4885        if (!sUserManager.exists(userId)) {
4886            Log.e(TAG, "No such user:" + userId);
4887            return;
4888        }
4889
4890        mContext.enforceCallingOrSelfPermission(
4891                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4892                "revokeRuntimePermission");
4893
4894        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4895                true /* requireFullPermission */, true /* checkShell */,
4896                "revokeRuntimePermission");
4897
4898        final int appId;
4899
4900        synchronized (mPackages) {
4901            final PackageParser.Package pkg = mPackages.get(packageName);
4902            if (pkg == null) {
4903                throw new IllegalArgumentException("Unknown package: " + packageName);
4904            }
4905
4906            final BasePermission bp = mSettings.mPermissions.get(name);
4907            if (bp == null) {
4908                throw new IllegalArgumentException("Unknown permission: " + name);
4909            }
4910
4911            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4912
4913            // If a permission review is required for legacy apps we represent
4914            // their permissions as always granted runtime ones since we need
4915            // to keep the review required permission flag per user while an
4916            // install permission's state is shared across all users.
4917            if (mPermissionReviewRequired
4918                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4919                    && bp.isRuntime()) {
4920                return;
4921            }
4922
4923            SettingBase sb = (SettingBase) pkg.mExtras;
4924            if (sb == null) {
4925                throw new IllegalArgumentException("Unknown package: " + packageName);
4926            }
4927
4928            final PermissionsState permissionsState = sb.getPermissionsState();
4929
4930            final int flags = permissionsState.getPermissionFlags(name, userId);
4931            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4932                throw new SecurityException("Cannot revoke system fixed permission "
4933                        + name + " for package " + packageName);
4934            }
4935            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4936                throw new SecurityException("Cannot revoke policy fixed permission "
4937                        + name + " for package " + packageName);
4938            }
4939
4940            if (bp.isDevelopment()) {
4941                // Development permissions must be handled specially, since they are not
4942                // normal runtime permissions.  For now they apply to all users.
4943                if (permissionsState.revokeInstallPermission(bp) !=
4944                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4945                    scheduleWriteSettingsLocked();
4946                }
4947                return;
4948            }
4949
4950            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4951                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4952                return;
4953            }
4954
4955            if (bp.isRuntime()) {
4956                logPermissionRevoked(mContext, name, packageName);
4957            }
4958
4959            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4960
4961            // Critical, after this call app should never have the permission.
4962            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4963
4964            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4965        }
4966
4967        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4968    }
4969
4970    /**
4971     * Get the first event id for the permission.
4972     *
4973     * <p>There are four events for each permission: <ul>
4974     *     <li>Request permission: first id + 0</li>
4975     *     <li>Grant permission: first id + 1</li>
4976     *     <li>Request for permission denied: first id + 2</li>
4977     *     <li>Revoke permission: first id + 3</li>
4978     * </ul></p>
4979     *
4980     * @param name name of the permission
4981     *
4982     * @return The first event id for the permission
4983     */
4984    private static int getBaseEventId(@NonNull String name) {
4985        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4986
4987        if (eventIdIndex == -1) {
4988            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4989                    || "user".equals(Build.TYPE)) {
4990                Log.i(TAG, "Unknown permission " + name);
4991
4992                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4993            } else {
4994                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4995                //
4996                // Also update
4997                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4998                // - metrics_constants.proto
4999                throw new IllegalStateException("Unknown permission " + name);
5000            }
5001        }
5002
5003        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5004    }
5005
5006    /**
5007     * Log that a permission was revoked.
5008     *
5009     * @param context Context of the caller
5010     * @param name name of the permission
5011     * @param packageName package permission if for
5012     */
5013    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5014            @NonNull String packageName) {
5015        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5016    }
5017
5018    /**
5019     * Log that a permission request was granted.
5020     *
5021     * @param context Context of the caller
5022     * @param name name of the permission
5023     * @param packageName package permission if for
5024     */
5025    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5026            @NonNull String packageName) {
5027        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5028    }
5029
5030    @Override
5031    public void resetRuntimePermissions() {
5032        mContext.enforceCallingOrSelfPermission(
5033                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5034                "revokeRuntimePermission");
5035
5036        int callingUid = Binder.getCallingUid();
5037        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5038            mContext.enforceCallingOrSelfPermission(
5039                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5040                    "resetRuntimePermissions");
5041        }
5042
5043        synchronized (mPackages) {
5044            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5045            for (int userId : UserManagerService.getInstance().getUserIds()) {
5046                final int packageCount = mPackages.size();
5047                for (int i = 0; i < packageCount; i++) {
5048                    PackageParser.Package pkg = mPackages.valueAt(i);
5049                    if (!(pkg.mExtras instanceof PackageSetting)) {
5050                        continue;
5051                    }
5052                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5053                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5054                }
5055            }
5056        }
5057    }
5058
5059    @Override
5060    public int getPermissionFlags(String name, String packageName, int userId) {
5061        if (!sUserManager.exists(userId)) {
5062            return 0;
5063        }
5064
5065        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5066
5067        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5068                true /* requireFullPermission */, false /* checkShell */,
5069                "getPermissionFlags");
5070
5071        synchronized (mPackages) {
5072            final PackageParser.Package pkg = mPackages.get(packageName);
5073            if (pkg == null) {
5074                return 0;
5075            }
5076
5077            final BasePermission bp = mSettings.mPermissions.get(name);
5078            if (bp == null) {
5079                return 0;
5080            }
5081
5082            SettingBase sb = (SettingBase) pkg.mExtras;
5083            if (sb == null) {
5084                return 0;
5085            }
5086
5087            PermissionsState permissionsState = sb.getPermissionsState();
5088            return permissionsState.getPermissionFlags(name, userId);
5089        }
5090    }
5091
5092    @Override
5093    public void updatePermissionFlags(String name, String packageName, int flagMask,
5094            int flagValues, int userId) {
5095        if (!sUserManager.exists(userId)) {
5096            return;
5097        }
5098
5099        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5100
5101        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5102                true /* requireFullPermission */, true /* checkShell */,
5103                "updatePermissionFlags");
5104
5105        // Only the system can change these flags and nothing else.
5106        if (getCallingUid() != Process.SYSTEM_UID) {
5107            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5108            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5109            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5110            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5111            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5112        }
5113
5114        synchronized (mPackages) {
5115            final PackageParser.Package pkg = mPackages.get(packageName);
5116            if (pkg == null) {
5117                throw new IllegalArgumentException("Unknown package: " + packageName);
5118            }
5119
5120            final BasePermission bp = mSettings.mPermissions.get(name);
5121            if (bp == null) {
5122                throw new IllegalArgumentException("Unknown permission: " + name);
5123            }
5124
5125            SettingBase sb = (SettingBase) pkg.mExtras;
5126            if (sb == null) {
5127                throw new IllegalArgumentException("Unknown package: " + packageName);
5128            }
5129
5130            PermissionsState permissionsState = sb.getPermissionsState();
5131
5132            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5133
5134            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5135                // Install and runtime permissions are stored in different places,
5136                // so figure out what permission changed and persist the change.
5137                if (permissionsState.getInstallPermissionState(name) != null) {
5138                    scheduleWriteSettingsLocked();
5139                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5140                        || hadState) {
5141                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5142                }
5143            }
5144        }
5145    }
5146
5147    /**
5148     * Update the permission flags for all packages and runtime permissions of a user in order
5149     * to allow device or profile owner to remove POLICY_FIXED.
5150     */
5151    @Override
5152    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5153        if (!sUserManager.exists(userId)) {
5154            return;
5155        }
5156
5157        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5158
5159        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5160                true /* requireFullPermission */, true /* checkShell */,
5161                "updatePermissionFlagsForAllApps");
5162
5163        // Only the system can change system fixed flags.
5164        if (getCallingUid() != Process.SYSTEM_UID) {
5165            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5166            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5167        }
5168
5169        synchronized (mPackages) {
5170            boolean changed = false;
5171            final int packageCount = mPackages.size();
5172            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5173                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5174                SettingBase sb = (SettingBase) pkg.mExtras;
5175                if (sb == null) {
5176                    continue;
5177                }
5178                PermissionsState permissionsState = sb.getPermissionsState();
5179                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5180                        userId, flagMask, flagValues);
5181            }
5182            if (changed) {
5183                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5184            }
5185        }
5186    }
5187
5188    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5189        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5190                != PackageManager.PERMISSION_GRANTED
5191            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5192                != PackageManager.PERMISSION_GRANTED) {
5193            throw new SecurityException(message + " requires "
5194                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5195                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5196        }
5197    }
5198
5199    @Override
5200    public boolean shouldShowRequestPermissionRationale(String permissionName,
5201            String packageName, int userId) {
5202        if (UserHandle.getCallingUserId() != userId) {
5203            mContext.enforceCallingPermission(
5204                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5205                    "canShowRequestPermissionRationale for user " + userId);
5206        }
5207
5208        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5209        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5210            return false;
5211        }
5212
5213        if (checkPermission(permissionName, packageName, userId)
5214                == PackageManager.PERMISSION_GRANTED) {
5215            return false;
5216        }
5217
5218        final int flags;
5219
5220        final long identity = Binder.clearCallingIdentity();
5221        try {
5222            flags = getPermissionFlags(permissionName,
5223                    packageName, userId);
5224        } finally {
5225            Binder.restoreCallingIdentity(identity);
5226        }
5227
5228        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5229                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5230                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5231
5232        if ((flags & fixedFlags) != 0) {
5233            return false;
5234        }
5235
5236        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5237    }
5238
5239    @Override
5240    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5241        mContext.enforceCallingOrSelfPermission(
5242                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5243                "addOnPermissionsChangeListener");
5244
5245        synchronized (mPackages) {
5246            mOnPermissionChangeListeners.addListenerLocked(listener);
5247        }
5248    }
5249
5250    @Override
5251    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5252        synchronized (mPackages) {
5253            mOnPermissionChangeListeners.removeListenerLocked(listener);
5254        }
5255    }
5256
5257    @Override
5258    public boolean isProtectedBroadcast(String actionName) {
5259        synchronized (mPackages) {
5260            if (mProtectedBroadcasts.contains(actionName)) {
5261                return true;
5262            } else if (actionName != null) {
5263                // TODO: remove these terrible hacks
5264                if (actionName.startsWith("android.net.netmon.lingerExpired")
5265                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5266                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5267                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5268                    return true;
5269                }
5270            }
5271        }
5272        return false;
5273    }
5274
5275    @Override
5276    public int checkSignatures(String pkg1, String pkg2) {
5277        synchronized (mPackages) {
5278            final PackageParser.Package p1 = mPackages.get(pkg1);
5279            final PackageParser.Package p2 = mPackages.get(pkg2);
5280            if (p1 == null || p1.mExtras == null
5281                    || p2 == null || p2.mExtras == null) {
5282                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5283            }
5284            return compareSignatures(p1.mSignatures, p2.mSignatures);
5285        }
5286    }
5287
5288    @Override
5289    public int checkUidSignatures(int uid1, int uid2) {
5290        // Map to base uids.
5291        uid1 = UserHandle.getAppId(uid1);
5292        uid2 = UserHandle.getAppId(uid2);
5293        // reader
5294        synchronized (mPackages) {
5295            Signature[] s1;
5296            Signature[] s2;
5297            Object obj = mSettings.getUserIdLPr(uid1);
5298            if (obj != null) {
5299                if (obj instanceof SharedUserSetting) {
5300                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5301                } else if (obj instanceof PackageSetting) {
5302                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5303                } else {
5304                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5305                }
5306            } else {
5307                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5308            }
5309            obj = mSettings.getUserIdLPr(uid2);
5310            if (obj != null) {
5311                if (obj instanceof SharedUserSetting) {
5312                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5313                } else if (obj instanceof PackageSetting) {
5314                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5315                } else {
5316                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5317                }
5318            } else {
5319                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5320            }
5321            return compareSignatures(s1, s2);
5322        }
5323    }
5324
5325    /**
5326     * This method should typically only be used when granting or revoking
5327     * permissions, since the app may immediately restart after this call.
5328     * <p>
5329     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5330     * guard your work against the app being relaunched.
5331     */
5332    private void killUid(int appId, int userId, String reason) {
5333        final long identity = Binder.clearCallingIdentity();
5334        try {
5335            IActivityManager am = ActivityManager.getService();
5336            if (am != null) {
5337                try {
5338                    am.killUid(appId, userId, reason);
5339                } catch (RemoteException e) {
5340                    /* ignore - same process */
5341                }
5342            }
5343        } finally {
5344            Binder.restoreCallingIdentity(identity);
5345        }
5346    }
5347
5348    /**
5349     * Compares two sets of signatures. Returns:
5350     * <br />
5351     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5352     * <br />
5353     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5354     * <br />
5355     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5356     * <br />
5357     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5358     * <br />
5359     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5360     */
5361    static int compareSignatures(Signature[] s1, Signature[] s2) {
5362        if (s1 == null) {
5363            return s2 == null
5364                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5365                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5366        }
5367
5368        if (s2 == null) {
5369            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5370        }
5371
5372        if (s1.length != s2.length) {
5373            return PackageManager.SIGNATURE_NO_MATCH;
5374        }
5375
5376        // Since both signature sets are of size 1, we can compare without HashSets.
5377        if (s1.length == 1) {
5378            return s1[0].equals(s2[0]) ?
5379                    PackageManager.SIGNATURE_MATCH :
5380                    PackageManager.SIGNATURE_NO_MATCH;
5381        }
5382
5383        ArraySet<Signature> set1 = new ArraySet<Signature>();
5384        for (Signature sig : s1) {
5385            set1.add(sig);
5386        }
5387        ArraySet<Signature> set2 = new ArraySet<Signature>();
5388        for (Signature sig : s2) {
5389            set2.add(sig);
5390        }
5391        // Make sure s2 contains all signatures in s1.
5392        if (set1.equals(set2)) {
5393            return PackageManager.SIGNATURE_MATCH;
5394        }
5395        return PackageManager.SIGNATURE_NO_MATCH;
5396    }
5397
5398    /**
5399     * If the database version for this type of package (internal storage or
5400     * external storage) is less than the version where package signatures
5401     * were updated, return true.
5402     */
5403    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5404        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5405        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5406    }
5407
5408    /**
5409     * Used for backward compatibility to make sure any packages with
5410     * certificate chains get upgraded to the new style. {@code existingSigs}
5411     * will be in the old format (since they were stored on disk from before the
5412     * system upgrade) and {@code scannedSigs} will be in the newer format.
5413     */
5414    private int compareSignaturesCompat(PackageSignatures existingSigs,
5415            PackageParser.Package scannedPkg) {
5416        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5417            return PackageManager.SIGNATURE_NO_MATCH;
5418        }
5419
5420        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5421        for (Signature sig : existingSigs.mSignatures) {
5422            existingSet.add(sig);
5423        }
5424        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5425        for (Signature sig : scannedPkg.mSignatures) {
5426            try {
5427                Signature[] chainSignatures = sig.getChainSignatures();
5428                for (Signature chainSig : chainSignatures) {
5429                    scannedCompatSet.add(chainSig);
5430                }
5431            } catch (CertificateEncodingException e) {
5432                scannedCompatSet.add(sig);
5433            }
5434        }
5435        /*
5436         * Make sure the expanded scanned set contains all signatures in the
5437         * existing one.
5438         */
5439        if (scannedCompatSet.equals(existingSet)) {
5440            // Migrate the old signatures to the new scheme.
5441            existingSigs.assignSignatures(scannedPkg.mSignatures);
5442            // The new KeySets will be re-added later in the scanning process.
5443            synchronized (mPackages) {
5444                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5445            }
5446            return PackageManager.SIGNATURE_MATCH;
5447        }
5448        return PackageManager.SIGNATURE_NO_MATCH;
5449    }
5450
5451    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5452        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5453        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5454    }
5455
5456    private int compareSignaturesRecover(PackageSignatures existingSigs,
5457            PackageParser.Package scannedPkg) {
5458        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5459            return PackageManager.SIGNATURE_NO_MATCH;
5460        }
5461
5462        String msg = null;
5463        try {
5464            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5465                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5466                        + scannedPkg.packageName);
5467                return PackageManager.SIGNATURE_MATCH;
5468            }
5469        } catch (CertificateException e) {
5470            msg = e.getMessage();
5471        }
5472
5473        logCriticalInfo(Log.INFO,
5474                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5475        return PackageManager.SIGNATURE_NO_MATCH;
5476    }
5477
5478    @Override
5479    public List<String> getAllPackages() {
5480        synchronized (mPackages) {
5481            return new ArrayList<String>(mPackages.keySet());
5482        }
5483    }
5484
5485    @Override
5486    public String[] getPackagesForUid(int uid) {
5487        final int userId = UserHandle.getUserId(uid);
5488        uid = UserHandle.getAppId(uid);
5489        // reader
5490        synchronized (mPackages) {
5491            Object obj = mSettings.getUserIdLPr(uid);
5492            if (obj instanceof SharedUserSetting) {
5493                final SharedUserSetting sus = (SharedUserSetting) obj;
5494                final int N = sus.packages.size();
5495                String[] res = new String[N];
5496                final Iterator<PackageSetting> it = sus.packages.iterator();
5497                int i = 0;
5498                while (it.hasNext()) {
5499                    PackageSetting ps = it.next();
5500                    if (ps.getInstalled(userId)) {
5501                        res[i++] = ps.name;
5502                    } else {
5503                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5504                    }
5505                }
5506                return res;
5507            } else if (obj instanceof PackageSetting) {
5508                final PackageSetting ps = (PackageSetting) obj;
5509                if (ps.getInstalled(userId)) {
5510                    return new String[]{ps.name};
5511                }
5512            }
5513        }
5514        return null;
5515    }
5516
5517    @Override
5518    public String getNameForUid(int uid) {
5519        // reader
5520        synchronized (mPackages) {
5521            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5522            if (obj instanceof SharedUserSetting) {
5523                final SharedUserSetting sus = (SharedUserSetting) obj;
5524                return sus.name + ":" + sus.userId;
5525            } else if (obj instanceof PackageSetting) {
5526                final PackageSetting ps = (PackageSetting) obj;
5527                return ps.name;
5528            }
5529        }
5530        return null;
5531    }
5532
5533    @Override
5534    public int getUidForSharedUser(String sharedUserName) {
5535        if(sharedUserName == null) {
5536            return -1;
5537        }
5538        // reader
5539        synchronized (mPackages) {
5540            SharedUserSetting suid;
5541            try {
5542                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5543                if (suid != null) {
5544                    return suid.userId;
5545                }
5546            } catch (PackageManagerException ignore) {
5547                // can't happen, but, still need to catch it
5548            }
5549            return -1;
5550        }
5551    }
5552
5553    @Override
5554    public int getFlagsForUid(int uid) {
5555        synchronized (mPackages) {
5556            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5557            if (obj instanceof SharedUserSetting) {
5558                final SharedUserSetting sus = (SharedUserSetting) obj;
5559                return sus.pkgFlags;
5560            } else if (obj instanceof PackageSetting) {
5561                final PackageSetting ps = (PackageSetting) obj;
5562                return ps.pkgFlags;
5563            }
5564        }
5565        return 0;
5566    }
5567
5568    @Override
5569    public int getPrivateFlagsForUid(int uid) {
5570        synchronized (mPackages) {
5571            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5572            if (obj instanceof SharedUserSetting) {
5573                final SharedUserSetting sus = (SharedUserSetting) obj;
5574                return sus.pkgPrivateFlags;
5575            } else if (obj instanceof PackageSetting) {
5576                final PackageSetting ps = (PackageSetting) obj;
5577                return ps.pkgPrivateFlags;
5578            }
5579        }
5580        return 0;
5581    }
5582
5583    @Override
5584    public boolean isUidPrivileged(int uid) {
5585        uid = UserHandle.getAppId(uid);
5586        // reader
5587        synchronized (mPackages) {
5588            Object obj = mSettings.getUserIdLPr(uid);
5589            if (obj instanceof SharedUserSetting) {
5590                final SharedUserSetting sus = (SharedUserSetting) obj;
5591                final Iterator<PackageSetting> it = sus.packages.iterator();
5592                while (it.hasNext()) {
5593                    if (it.next().isPrivileged()) {
5594                        return true;
5595                    }
5596                }
5597            } else if (obj instanceof PackageSetting) {
5598                final PackageSetting ps = (PackageSetting) obj;
5599                return ps.isPrivileged();
5600            }
5601        }
5602        return false;
5603    }
5604
5605    @Override
5606    public String[] getAppOpPermissionPackages(String permissionName) {
5607        synchronized (mPackages) {
5608            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5609            if (pkgs == null) {
5610                return null;
5611            }
5612            return pkgs.toArray(new String[pkgs.size()]);
5613        }
5614    }
5615
5616    @Override
5617    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5618            int flags, int userId) {
5619        return resolveIntentInternal(
5620                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5621    }
5622
5623    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5624            int flags, int userId, boolean includeInstantApps) {
5625        try {
5626            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5627
5628            if (!sUserManager.exists(userId)) return null;
5629            final int callingUid = Binder.getCallingUid();
5630            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5631            enforceCrossUserPermission(callingUid, userId,
5632                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5633
5634            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5635            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5636                    flags, userId, includeInstantApps);
5637            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5638
5639            final ResolveInfo bestChoice =
5640                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5641            return bestChoice;
5642        } finally {
5643            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5644        }
5645    }
5646
5647    @Override
5648    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5649        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5650            throw new SecurityException(
5651                    "findPersistentPreferredActivity can only be run by the system");
5652        }
5653        if (!sUserManager.exists(userId)) {
5654            return null;
5655        }
5656        final int callingUid = Binder.getCallingUid();
5657        intent = updateIntentForResolve(intent);
5658        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5659        final int flags = updateFlagsForResolve(
5660                0, userId, intent, callingUid, false /*includeInstantApps*/);
5661        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5662                userId);
5663        synchronized (mPackages) {
5664            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5665                    userId);
5666        }
5667    }
5668
5669    @Override
5670    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5671            IntentFilter filter, int match, ComponentName activity) {
5672        final int userId = UserHandle.getCallingUserId();
5673        if (DEBUG_PREFERRED) {
5674            Log.v(TAG, "setLastChosenActivity intent=" + intent
5675                + " resolvedType=" + resolvedType
5676                + " flags=" + flags
5677                + " filter=" + filter
5678                + " match=" + match
5679                + " activity=" + activity);
5680            filter.dump(new PrintStreamPrinter(System.out), "    ");
5681        }
5682        intent.setComponent(null);
5683        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5684                userId);
5685        // Find any earlier preferred or last chosen entries and nuke them
5686        findPreferredActivity(intent, resolvedType,
5687                flags, query, 0, false, true, false, userId);
5688        // Add the new activity as the last chosen for this filter
5689        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5690                "Setting last chosen");
5691    }
5692
5693    @Override
5694    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5695        final int userId = UserHandle.getCallingUserId();
5696        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5697        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5698                userId);
5699        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5700                false, false, false, userId);
5701    }
5702
5703    /**
5704     * Returns whether or not instant apps have been disabled remotely.
5705     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5706     * held. Otherwise we run the risk of deadlock.
5707     */
5708    private boolean isEphemeralDisabled() {
5709        // ephemeral apps have been disabled across the board
5710        if (DISABLE_EPHEMERAL_APPS) {
5711            return true;
5712        }
5713        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5714        if (!mSystemReady) {
5715            return true;
5716        }
5717        // we can't get a content resolver until the system is ready; these checks must happen last
5718        final ContentResolver resolver = mContext.getContentResolver();
5719        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5720            return true;
5721        }
5722        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5723    }
5724
5725    private boolean isEphemeralAllowed(
5726            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5727            boolean skipPackageCheck) {
5728        final int callingUser = UserHandle.getCallingUserId();
5729        if (callingUser != UserHandle.USER_SYSTEM) {
5730            return false;
5731        }
5732        if (mInstantAppResolverConnection == null) {
5733            return false;
5734        }
5735        if (mInstantAppInstallerComponent == null) {
5736            return false;
5737        }
5738        if (intent.getComponent() != null) {
5739            return false;
5740        }
5741        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5742            return false;
5743        }
5744        if (!skipPackageCheck && intent.getPackage() != null) {
5745            return false;
5746        }
5747        final boolean isWebUri = hasWebURI(intent);
5748        if (!isWebUri || intent.getData().getHost() == null) {
5749            return false;
5750        }
5751        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5752        // Or if there's already an ephemeral app installed that handles the action
5753        synchronized (mPackages) {
5754            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5755            for (int n = 0; n < count; n++) {
5756                final ResolveInfo info = resolvedActivities.get(n);
5757                final String packageName = info.activityInfo.packageName;
5758                final PackageSetting ps = mSettings.mPackages.get(packageName);
5759                if (ps != null) {
5760                    // only check domain verification status if the app is not a browser
5761                    if (!info.handleAllWebDataURI) {
5762                        // Try to get the status from User settings first
5763                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5764                        final int status = (int) (packedStatus >> 32);
5765                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5766                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5767                            if (DEBUG_EPHEMERAL) {
5768                                Slog.v(TAG, "DENY instant app;"
5769                                    + " pkg: " + packageName + ", status: " + status);
5770                            }
5771                            return false;
5772                        }
5773                    }
5774                    if (ps.getInstantApp(userId)) {
5775                        if (DEBUG_EPHEMERAL) {
5776                            Slog.v(TAG, "DENY instant app installed;"
5777                                    + " pkg: " + packageName);
5778                        }
5779                        return false;
5780                    }
5781                }
5782            }
5783        }
5784        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5785        return true;
5786    }
5787
5788    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5789            Intent origIntent, String resolvedType, String callingPackage,
5790            int userId) {
5791        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5792                new InstantAppRequest(responseObj, origIntent, resolvedType,
5793                        callingPackage, userId));
5794        mHandler.sendMessage(msg);
5795    }
5796
5797    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5798            int flags, List<ResolveInfo> query, int userId) {
5799        if (query != null) {
5800            final int N = query.size();
5801            if (N == 1) {
5802                return query.get(0);
5803            } else if (N > 1) {
5804                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5805                // If there is more than one activity with the same priority,
5806                // then let the user decide between them.
5807                ResolveInfo r0 = query.get(0);
5808                ResolveInfo r1 = query.get(1);
5809                if (DEBUG_INTENT_MATCHING || debug) {
5810                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5811                            + r1.activityInfo.name + "=" + r1.priority);
5812                }
5813                // If the first activity has a higher priority, or a different
5814                // default, then it is always desirable to pick it.
5815                if (r0.priority != r1.priority
5816                        || r0.preferredOrder != r1.preferredOrder
5817                        || r0.isDefault != r1.isDefault) {
5818                    return query.get(0);
5819                }
5820                // If we have saved a preference for a preferred activity for
5821                // this Intent, use that.
5822                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5823                        flags, query, r0.priority, true, false, debug, userId);
5824                if (ri != null) {
5825                    return ri;
5826                }
5827                // If we have an ephemeral app, use it
5828                for (int i = 0; i < N; i++) {
5829                    ri = query.get(i);
5830                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5831                        return ri;
5832                    }
5833                }
5834                ri = new ResolveInfo(mResolveInfo);
5835                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5836                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5837                // If all of the options come from the same package, show the application's
5838                // label and icon instead of the generic resolver's.
5839                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5840                // and then throw away the ResolveInfo itself, meaning that the caller loses
5841                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5842                // a fallback for this case; we only set the target package's resources on
5843                // the ResolveInfo, not the ActivityInfo.
5844                final String intentPackage = intent.getPackage();
5845                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5846                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5847                    ri.resolvePackageName = intentPackage;
5848                    if (userNeedsBadging(userId)) {
5849                        ri.noResourceId = true;
5850                    } else {
5851                        ri.icon = appi.icon;
5852                    }
5853                    ri.iconResourceId = appi.icon;
5854                    ri.labelRes = appi.labelRes;
5855                }
5856                ri.activityInfo.applicationInfo = new ApplicationInfo(
5857                        ri.activityInfo.applicationInfo);
5858                if (userId != 0) {
5859                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5860                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5861                }
5862                // Make sure that the resolver is displayable in car mode
5863                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5864                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5865                return ri;
5866            }
5867        }
5868        return null;
5869    }
5870
5871    /**
5872     * Return true if the given list is not empty and all of its contents have
5873     * an activityInfo with the given package name.
5874     */
5875    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5876        if (ArrayUtils.isEmpty(list)) {
5877            return false;
5878        }
5879        for (int i = 0, N = list.size(); i < N; i++) {
5880            final ResolveInfo ri = list.get(i);
5881            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5882            if (ai == null || !packageName.equals(ai.packageName)) {
5883                return false;
5884            }
5885        }
5886        return true;
5887    }
5888
5889    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5890            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5891        final int N = query.size();
5892        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5893                .get(userId);
5894        // Get the list of persistent preferred activities that handle the intent
5895        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5896        List<PersistentPreferredActivity> pprefs = ppir != null
5897                ? ppir.queryIntent(intent, resolvedType,
5898                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5899                        userId)
5900                : null;
5901        if (pprefs != null && pprefs.size() > 0) {
5902            final int M = pprefs.size();
5903            for (int i=0; i<M; i++) {
5904                final PersistentPreferredActivity ppa = pprefs.get(i);
5905                if (DEBUG_PREFERRED || debug) {
5906                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5907                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5908                            + "\n  component=" + ppa.mComponent);
5909                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5910                }
5911                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5912                        flags | MATCH_DISABLED_COMPONENTS, userId);
5913                if (DEBUG_PREFERRED || debug) {
5914                    Slog.v(TAG, "Found persistent preferred activity:");
5915                    if (ai != null) {
5916                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5917                    } else {
5918                        Slog.v(TAG, "  null");
5919                    }
5920                }
5921                if (ai == null) {
5922                    // This previously registered persistent preferred activity
5923                    // component is no longer known. Ignore it and do NOT remove it.
5924                    continue;
5925                }
5926                for (int j=0; j<N; j++) {
5927                    final ResolveInfo ri = query.get(j);
5928                    if (!ri.activityInfo.applicationInfo.packageName
5929                            .equals(ai.applicationInfo.packageName)) {
5930                        continue;
5931                    }
5932                    if (!ri.activityInfo.name.equals(ai.name)) {
5933                        continue;
5934                    }
5935                    //  Found a persistent preference that can handle the intent.
5936                    if (DEBUG_PREFERRED || debug) {
5937                        Slog.v(TAG, "Returning persistent preferred activity: " +
5938                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5939                    }
5940                    return ri;
5941                }
5942            }
5943        }
5944        return null;
5945    }
5946
5947    // TODO: handle preferred activities missing while user has amnesia
5948    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5949            List<ResolveInfo> query, int priority, boolean always,
5950            boolean removeMatches, boolean debug, int userId) {
5951        if (!sUserManager.exists(userId)) return null;
5952        final int callingUid = Binder.getCallingUid();
5953        flags = updateFlagsForResolve(
5954                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5955        intent = updateIntentForResolve(intent);
5956        // writer
5957        synchronized (mPackages) {
5958            // Try to find a matching persistent preferred activity.
5959            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5960                    debug, userId);
5961
5962            // If a persistent preferred activity matched, use it.
5963            if (pri != null) {
5964                return pri;
5965            }
5966
5967            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5968            // Get the list of preferred activities that handle the intent
5969            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5970            List<PreferredActivity> prefs = pir != null
5971                    ? pir.queryIntent(intent, resolvedType,
5972                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5973                            userId)
5974                    : null;
5975            if (prefs != null && prefs.size() > 0) {
5976                boolean changed = false;
5977                try {
5978                    // First figure out how good the original match set is.
5979                    // We will only allow preferred activities that came
5980                    // from the same match quality.
5981                    int match = 0;
5982
5983                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5984
5985                    final int N = query.size();
5986                    for (int j=0; j<N; j++) {
5987                        final ResolveInfo ri = query.get(j);
5988                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5989                                + ": 0x" + Integer.toHexString(match));
5990                        if (ri.match > match) {
5991                            match = ri.match;
5992                        }
5993                    }
5994
5995                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5996                            + Integer.toHexString(match));
5997
5998                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5999                    final int M = prefs.size();
6000                    for (int i=0; i<M; i++) {
6001                        final PreferredActivity pa = prefs.get(i);
6002                        if (DEBUG_PREFERRED || debug) {
6003                            Slog.v(TAG, "Checking PreferredActivity ds="
6004                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6005                                    + "\n  component=" + pa.mPref.mComponent);
6006                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6007                        }
6008                        if (pa.mPref.mMatch != match) {
6009                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6010                                    + Integer.toHexString(pa.mPref.mMatch));
6011                            continue;
6012                        }
6013                        // If it's not an "always" type preferred activity and that's what we're
6014                        // looking for, skip it.
6015                        if (always && !pa.mPref.mAlways) {
6016                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6017                            continue;
6018                        }
6019                        final ActivityInfo ai = getActivityInfo(
6020                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6021                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6022                                userId);
6023                        if (DEBUG_PREFERRED || debug) {
6024                            Slog.v(TAG, "Found preferred activity:");
6025                            if (ai != null) {
6026                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6027                            } else {
6028                                Slog.v(TAG, "  null");
6029                            }
6030                        }
6031                        if (ai == null) {
6032                            // This previously registered preferred activity
6033                            // component is no longer known.  Most likely an update
6034                            // to the app was installed and in the new version this
6035                            // component no longer exists.  Clean it up by removing
6036                            // it from the preferred activities list, and skip it.
6037                            Slog.w(TAG, "Removing dangling preferred activity: "
6038                                    + pa.mPref.mComponent);
6039                            pir.removeFilter(pa);
6040                            changed = true;
6041                            continue;
6042                        }
6043                        for (int j=0; j<N; j++) {
6044                            final ResolveInfo ri = query.get(j);
6045                            if (!ri.activityInfo.applicationInfo.packageName
6046                                    .equals(ai.applicationInfo.packageName)) {
6047                                continue;
6048                            }
6049                            if (!ri.activityInfo.name.equals(ai.name)) {
6050                                continue;
6051                            }
6052
6053                            if (removeMatches) {
6054                                pir.removeFilter(pa);
6055                                changed = true;
6056                                if (DEBUG_PREFERRED) {
6057                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6058                                }
6059                                break;
6060                            }
6061
6062                            // Okay we found a previously set preferred or last chosen app.
6063                            // If the result set is different from when this
6064                            // was created, we need to clear it and re-ask the
6065                            // user their preference, if we're looking for an "always" type entry.
6066                            if (always && !pa.mPref.sameSet(query)) {
6067                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6068                                        + intent + " type " + resolvedType);
6069                                if (DEBUG_PREFERRED) {
6070                                    Slog.v(TAG, "Removing preferred activity since set changed "
6071                                            + pa.mPref.mComponent);
6072                                }
6073                                pir.removeFilter(pa);
6074                                // Re-add the filter as a "last chosen" entry (!always)
6075                                PreferredActivity lastChosen = new PreferredActivity(
6076                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6077                                pir.addFilter(lastChosen);
6078                                changed = true;
6079                                return null;
6080                            }
6081
6082                            // Yay! Either the set matched or we're looking for the last chosen
6083                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6084                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6085                            return ri;
6086                        }
6087                    }
6088                } finally {
6089                    if (changed) {
6090                        if (DEBUG_PREFERRED) {
6091                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6092                        }
6093                        scheduleWritePackageRestrictionsLocked(userId);
6094                    }
6095                }
6096            }
6097        }
6098        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6099        return null;
6100    }
6101
6102    /*
6103     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6104     */
6105    @Override
6106    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6107            int targetUserId) {
6108        mContext.enforceCallingOrSelfPermission(
6109                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6110        List<CrossProfileIntentFilter> matches =
6111                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6112        if (matches != null) {
6113            int size = matches.size();
6114            for (int i = 0; i < size; i++) {
6115                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6116            }
6117        }
6118        if (hasWebURI(intent)) {
6119            // cross-profile app linking works only towards the parent.
6120            final int callingUid = Binder.getCallingUid();
6121            final UserInfo parent = getProfileParent(sourceUserId);
6122            synchronized(mPackages) {
6123                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6124                        false /*includeInstantApps*/);
6125                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6126                        intent, resolvedType, flags, sourceUserId, parent.id);
6127                return xpDomainInfo != null;
6128            }
6129        }
6130        return false;
6131    }
6132
6133    private UserInfo getProfileParent(int userId) {
6134        final long identity = Binder.clearCallingIdentity();
6135        try {
6136            return sUserManager.getProfileParent(userId);
6137        } finally {
6138            Binder.restoreCallingIdentity(identity);
6139        }
6140    }
6141
6142    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6143            String resolvedType, int userId) {
6144        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6145        if (resolver != null) {
6146            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6147        }
6148        return null;
6149    }
6150
6151    @Override
6152    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6153            String resolvedType, int flags, int userId) {
6154        try {
6155            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6156
6157            return new ParceledListSlice<>(
6158                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6159        } finally {
6160            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6161        }
6162    }
6163
6164    /**
6165     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6166     * instant, returns {@code null}.
6167     */
6168    private String getInstantAppPackageName(int callingUid) {
6169        // If the caller is an isolated app use the owner's uid for the lookup.
6170        if (Process.isIsolated(callingUid)) {
6171            callingUid = mIsolatedOwners.get(callingUid);
6172        }
6173        final int appId = UserHandle.getAppId(callingUid);
6174        synchronized (mPackages) {
6175            final Object obj = mSettings.getUserIdLPr(appId);
6176            if (obj instanceof PackageSetting) {
6177                final PackageSetting ps = (PackageSetting) obj;
6178                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6179                return isInstantApp ? ps.pkg.packageName : null;
6180            }
6181        }
6182        return null;
6183    }
6184
6185    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6186            String resolvedType, int flags, int userId) {
6187        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6188    }
6189
6190    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6191            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6192        if (!sUserManager.exists(userId)) return Collections.emptyList();
6193        final int callingUid = Binder.getCallingUid();
6194        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6195        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6196        enforceCrossUserPermission(callingUid, userId,
6197                false /* requireFullPermission */, false /* checkShell */,
6198                "query intent activities");
6199        ComponentName comp = intent.getComponent();
6200        if (comp == null) {
6201            if (intent.getSelector() != null) {
6202                intent = intent.getSelector();
6203                comp = intent.getComponent();
6204            }
6205        }
6206
6207        if (comp != null) {
6208            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6209            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6210            if (ai != null) {
6211                // When specifying an explicit component, we prevent the activity from being
6212                // used when either 1) the calling package is normal and the activity is within
6213                // an ephemeral application or 2) the calling package is ephemeral and the
6214                // activity is not visible to ephemeral applications.
6215                final boolean matchInstantApp =
6216                        (flags & PackageManager.MATCH_INSTANT) != 0;
6217                final boolean matchVisibleToInstantAppOnly =
6218                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6219                final boolean isCallerInstantApp =
6220                        instantAppPkgName != null;
6221                final boolean isTargetSameInstantApp =
6222                        comp.getPackageName().equals(instantAppPkgName);
6223                final boolean isTargetInstantApp =
6224                        (ai.applicationInfo.privateFlags
6225                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6226                final boolean isTargetHiddenFromInstantApp =
6227                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6228                final boolean blockResolution =
6229                        !isTargetSameInstantApp
6230                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6231                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6232                                        && isTargetHiddenFromInstantApp));
6233                if (!blockResolution) {
6234                    final ResolveInfo ri = new ResolveInfo();
6235                    ri.activityInfo = ai;
6236                    list.add(ri);
6237                }
6238            }
6239            return applyPostResolutionFilter(list, instantAppPkgName);
6240        }
6241
6242        // reader
6243        boolean sortResult = false;
6244        boolean addEphemeral = false;
6245        List<ResolveInfo> result;
6246        final String pkgName = intent.getPackage();
6247        final boolean ephemeralDisabled = isEphemeralDisabled();
6248        synchronized (mPackages) {
6249            if (pkgName == null) {
6250                List<CrossProfileIntentFilter> matchingFilters =
6251                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6252                // Check for results that need to skip the current profile.
6253                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6254                        resolvedType, flags, userId);
6255                if (xpResolveInfo != null) {
6256                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6257                    xpResult.add(xpResolveInfo);
6258                    return applyPostResolutionFilter(
6259                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6260                }
6261
6262                // Check for results in the current profile.
6263                result = filterIfNotSystemUser(mActivities.queryIntent(
6264                        intent, resolvedType, flags, userId), userId);
6265                addEphemeral = !ephemeralDisabled
6266                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6267                // Check for cross profile results.
6268                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6269                xpResolveInfo = queryCrossProfileIntents(
6270                        matchingFilters, intent, resolvedType, flags, userId,
6271                        hasNonNegativePriorityResult);
6272                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6273                    boolean isVisibleToUser = filterIfNotSystemUser(
6274                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6275                    if (isVisibleToUser) {
6276                        result.add(xpResolveInfo);
6277                        sortResult = true;
6278                    }
6279                }
6280                if (hasWebURI(intent)) {
6281                    CrossProfileDomainInfo xpDomainInfo = null;
6282                    final UserInfo parent = getProfileParent(userId);
6283                    if (parent != null) {
6284                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6285                                flags, userId, parent.id);
6286                    }
6287                    if (xpDomainInfo != null) {
6288                        if (xpResolveInfo != null) {
6289                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6290                            // in the result.
6291                            result.remove(xpResolveInfo);
6292                        }
6293                        if (result.size() == 0 && !addEphemeral) {
6294                            // No result in current profile, but found candidate in parent user.
6295                            // And we are not going to add emphemeral app, so we can return the
6296                            // result straight away.
6297                            result.add(xpDomainInfo.resolveInfo);
6298                            return applyPostResolutionFilter(result, instantAppPkgName);
6299                        }
6300                    } else if (result.size() <= 1 && !addEphemeral) {
6301                        // No result in parent user and <= 1 result in current profile, and we
6302                        // are not going to add emphemeral app, so we can return the result without
6303                        // further processing.
6304                        return applyPostResolutionFilter(result, instantAppPkgName);
6305                    }
6306                    // We have more than one candidate (combining results from current and parent
6307                    // profile), so we need filtering and sorting.
6308                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6309                            intent, flags, result, xpDomainInfo, userId);
6310                    sortResult = true;
6311                }
6312            } else {
6313                final PackageParser.Package pkg = mPackages.get(pkgName);
6314                if (pkg != null) {
6315                    return applyPostResolutionFilter(filterIfNotSystemUser(
6316                            mActivities.queryIntentForPackage(
6317                                    intent, resolvedType, flags, pkg.activities, userId),
6318                            userId), instantAppPkgName);
6319                } else {
6320                    // the caller wants to resolve for a particular package; however, there
6321                    // were no installed results, so, try to find an ephemeral result
6322                    addEphemeral = !ephemeralDisabled
6323                            && isEphemeralAllowed(
6324                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6325                    result = new ArrayList<ResolveInfo>();
6326                }
6327            }
6328        }
6329        if (addEphemeral) {
6330            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6331            final InstantAppRequest requestObject = new InstantAppRequest(
6332                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6333                    null /*callingPackage*/, userId);
6334            final AuxiliaryResolveInfo auxiliaryResponse =
6335                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6336                            mContext, mInstantAppResolverConnection, requestObject);
6337            if (auxiliaryResponse != null) {
6338                if (DEBUG_EPHEMERAL) {
6339                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6340                }
6341                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6342                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6343                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6344                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6345                // make sure this resolver is the default
6346                ephemeralInstaller.isDefault = true;
6347                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6348                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6349                // add a non-generic filter
6350                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6351                ephemeralInstaller.filter.addDataPath(
6352                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6353                ephemeralInstaller.instantAppAvailable = true;
6354                result.add(ephemeralInstaller);
6355            }
6356            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6357        }
6358        if (sortResult) {
6359            Collections.sort(result, mResolvePrioritySorter);
6360        }
6361        return applyPostResolutionFilter(result, instantAppPkgName);
6362    }
6363
6364    private static class CrossProfileDomainInfo {
6365        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6366        ResolveInfo resolveInfo;
6367        /* Best domain verification status of the activities found in the other profile */
6368        int bestDomainVerificationStatus;
6369    }
6370
6371    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6372            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6373        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6374                sourceUserId)) {
6375            return null;
6376        }
6377        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6378                resolvedType, flags, parentUserId);
6379
6380        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6381            return null;
6382        }
6383        CrossProfileDomainInfo result = null;
6384        int size = resultTargetUser.size();
6385        for (int i = 0; i < size; i++) {
6386            ResolveInfo riTargetUser = resultTargetUser.get(i);
6387            // Intent filter verification is only for filters that specify a host. So don't return
6388            // those that handle all web uris.
6389            if (riTargetUser.handleAllWebDataURI) {
6390                continue;
6391            }
6392            String packageName = riTargetUser.activityInfo.packageName;
6393            PackageSetting ps = mSettings.mPackages.get(packageName);
6394            if (ps == null) {
6395                continue;
6396            }
6397            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6398            int status = (int)(verificationState >> 32);
6399            if (result == null) {
6400                result = new CrossProfileDomainInfo();
6401                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6402                        sourceUserId, parentUserId);
6403                result.bestDomainVerificationStatus = status;
6404            } else {
6405                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6406                        result.bestDomainVerificationStatus);
6407            }
6408        }
6409        // Don't consider matches with status NEVER across profiles.
6410        if (result != null && result.bestDomainVerificationStatus
6411                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6412            return null;
6413        }
6414        return result;
6415    }
6416
6417    /**
6418     * Verification statuses are ordered from the worse to the best, except for
6419     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6420     */
6421    private int bestDomainVerificationStatus(int status1, int status2) {
6422        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6423            return status2;
6424        }
6425        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6426            return status1;
6427        }
6428        return (int) MathUtils.max(status1, status2);
6429    }
6430
6431    private boolean isUserEnabled(int userId) {
6432        long callingId = Binder.clearCallingIdentity();
6433        try {
6434            UserInfo userInfo = sUserManager.getUserInfo(userId);
6435            return userInfo != null && userInfo.isEnabled();
6436        } finally {
6437            Binder.restoreCallingIdentity(callingId);
6438        }
6439    }
6440
6441    /**
6442     * Filter out activities with systemUserOnly flag set, when current user is not System.
6443     *
6444     * @return filtered list
6445     */
6446    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6447        if (userId == UserHandle.USER_SYSTEM) {
6448            return resolveInfos;
6449        }
6450        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6451            ResolveInfo info = resolveInfos.get(i);
6452            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6453                resolveInfos.remove(i);
6454            }
6455        }
6456        return resolveInfos;
6457    }
6458
6459    /**
6460     * Filters out ephemeral activities.
6461     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6462     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6463     *
6464     * @param resolveInfos The pre-filtered list of resolved activities
6465     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6466     *          is performed.
6467     * @return A filtered list of resolved activities.
6468     */
6469    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6470            String ephemeralPkgName) {
6471        // TODO: When adding on-demand split support for non-instant apps, remove this check
6472        // and always apply post filtering
6473        if (ephemeralPkgName == null) {
6474            return resolveInfos;
6475        }
6476        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6477            final ResolveInfo info = resolveInfos.get(i);
6478            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6479            // allow activities that are defined in the provided package
6480            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6481                if (info.activityInfo.splitName != null
6482                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6483                                info.activityInfo.splitName)) {
6484                    // requested activity is defined in a split that hasn't been installed yet.
6485                    // add the installer to the resolve list
6486                    if (DEBUG_EPHEMERAL) {
6487                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6488                    }
6489                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6490                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6491                            info.activityInfo.packageName, info.activityInfo.splitName,
6492                            info.activityInfo.applicationInfo.versionCode);
6493                    // make sure this resolver is the default
6494                    installerInfo.isDefault = true;
6495                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6496                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6497                    // add a non-generic filter
6498                    installerInfo.filter = new IntentFilter();
6499                    // load resources from the correct package
6500                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6501                    resolveInfos.set(i, installerInfo);
6502                }
6503                continue;
6504            }
6505            // allow activities that have been explicitly exposed to ephemeral apps
6506            if (!isEphemeralApp
6507                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6508                continue;
6509            }
6510            resolveInfos.remove(i);
6511        }
6512        return resolveInfos;
6513    }
6514
6515    /**
6516     * @param resolveInfos list of resolve infos in descending priority order
6517     * @return if the list contains a resolve info with non-negative priority
6518     */
6519    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6520        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6521    }
6522
6523    private static boolean hasWebURI(Intent intent) {
6524        if (intent.getData() == null) {
6525            return false;
6526        }
6527        final String scheme = intent.getScheme();
6528        if (TextUtils.isEmpty(scheme)) {
6529            return false;
6530        }
6531        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6532    }
6533
6534    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6535            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6536            int userId) {
6537        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6538
6539        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6540            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6541                    candidates.size());
6542        }
6543
6544        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6545        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6546        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6547        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6548        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6549        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6550
6551        synchronized (mPackages) {
6552            final int count = candidates.size();
6553            // First, try to use linked apps. Partition the candidates into four lists:
6554            // one for the final results, one for the "do not use ever", one for "undefined status"
6555            // and finally one for "browser app type".
6556            for (int n=0; n<count; n++) {
6557                ResolveInfo info = candidates.get(n);
6558                String packageName = info.activityInfo.packageName;
6559                PackageSetting ps = mSettings.mPackages.get(packageName);
6560                if (ps != null) {
6561                    // Add to the special match all list (Browser use case)
6562                    if (info.handleAllWebDataURI) {
6563                        matchAllList.add(info);
6564                        continue;
6565                    }
6566                    // Try to get the status from User settings first
6567                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6568                    int status = (int)(packedStatus >> 32);
6569                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6570                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6571                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6572                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6573                                    + " : linkgen=" + linkGeneration);
6574                        }
6575                        // Use link-enabled generation as preferredOrder, i.e.
6576                        // prefer newly-enabled over earlier-enabled.
6577                        info.preferredOrder = linkGeneration;
6578                        alwaysList.add(info);
6579                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6580                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6581                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6582                        }
6583                        neverList.add(info);
6584                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6585                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6586                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6587                        }
6588                        alwaysAskList.add(info);
6589                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6590                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6591                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6592                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6593                        }
6594                        undefinedList.add(info);
6595                    }
6596                }
6597            }
6598
6599            // We'll want to include browser possibilities in a few cases
6600            boolean includeBrowser = false;
6601
6602            // First try to add the "always" resolution(s) for the current user, if any
6603            if (alwaysList.size() > 0) {
6604                result.addAll(alwaysList);
6605            } else {
6606                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6607                result.addAll(undefinedList);
6608                // Maybe add one for the other profile.
6609                if (xpDomainInfo != null && (
6610                        xpDomainInfo.bestDomainVerificationStatus
6611                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6612                    result.add(xpDomainInfo.resolveInfo);
6613                }
6614                includeBrowser = true;
6615            }
6616
6617            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6618            // If there were 'always' entries their preferred order has been set, so we also
6619            // back that off to make the alternatives equivalent
6620            if (alwaysAskList.size() > 0) {
6621                for (ResolveInfo i : result) {
6622                    i.preferredOrder = 0;
6623                }
6624                result.addAll(alwaysAskList);
6625                includeBrowser = true;
6626            }
6627
6628            if (includeBrowser) {
6629                // Also add browsers (all of them or only the default one)
6630                if (DEBUG_DOMAIN_VERIFICATION) {
6631                    Slog.v(TAG, "   ...including browsers in candidate set");
6632                }
6633                if ((matchFlags & MATCH_ALL) != 0) {
6634                    result.addAll(matchAllList);
6635                } else {
6636                    // Browser/generic handling case.  If there's a default browser, go straight
6637                    // to that (but only if there is no other higher-priority match).
6638                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6639                    int maxMatchPrio = 0;
6640                    ResolveInfo defaultBrowserMatch = null;
6641                    final int numCandidates = matchAllList.size();
6642                    for (int n = 0; n < numCandidates; n++) {
6643                        ResolveInfo info = matchAllList.get(n);
6644                        // track the highest overall match priority...
6645                        if (info.priority > maxMatchPrio) {
6646                            maxMatchPrio = info.priority;
6647                        }
6648                        // ...and the highest-priority default browser match
6649                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6650                            if (defaultBrowserMatch == null
6651                                    || (defaultBrowserMatch.priority < info.priority)) {
6652                                if (debug) {
6653                                    Slog.v(TAG, "Considering default browser match " + info);
6654                                }
6655                                defaultBrowserMatch = info;
6656                            }
6657                        }
6658                    }
6659                    if (defaultBrowserMatch != null
6660                            && defaultBrowserMatch.priority >= maxMatchPrio
6661                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6662                    {
6663                        if (debug) {
6664                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6665                        }
6666                        result.add(defaultBrowserMatch);
6667                    } else {
6668                        result.addAll(matchAllList);
6669                    }
6670                }
6671
6672                // If there is nothing selected, add all candidates and remove the ones that the user
6673                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6674                if (result.size() == 0) {
6675                    result.addAll(candidates);
6676                    result.removeAll(neverList);
6677                }
6678            }
6679        }
6680        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6681            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6682                    result.size());
6683            for (ResolveInfo info : result) {
6684                Slog.v(TAG, "  + " + info.activityInfo);
6685            }
6686        }
6687        return result;
6688    }
6689
6690    // Returns a packed value as a long:
6691    //
6692    // high 'int'-sized word: link status: undefined/ask/never/always.
6693    // low 'int'-sized word: relative priority among 'always' results.
6694    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6695        long result = ps.getDomainVerificationStatusForUser(userId);
6696        // if none available, get the master status
6697        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6698            if (ps.getIntentFilterVerificationInfo() != null) {
6699                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6700            }
6701        }
6702        return result;
6703    }
6704
6705    private ResolveInfo querySkipCurrentProfileIntents(
6706            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6707            int flags, int sourceUserId) {
6708        if (matchingFilters != null) {
6709            int size = matchingFilters.size();
6710            for (int i = 0; i < size; i ++) {
6711                CrossProfileIntentFilter filter = matchingFilters.get(i);
6712                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6713                    // Checking if there are activities in the target user that can handle the
6714                    // intent.
6715                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6716                            resolvedType, flags, sourceUserId);
6717                    if (resolveInfo != null) {
6718                        return resolveInfo;
6719                    }
6720                }
6721            }
6722        }
6723        return null;
6724    }
6725
6726    // Return matching ResolveInfo in target user if any.
6727    private ResolveInfo queryCrossProfileIntents(
6728            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6729            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6730        if (matchingFilters != null) {
6731            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6732            // match the same intent. For performance reasons, it is better not to
6733            // run queryIntent twice for the same userId
6734            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6735            int size = matchingFilters.size();
6736            for (int i = 0; i < size; i++) {
6737                CrossProfileIntentFilter filter = matchingFilters.get(i);
6738                int targetUserId = filter.getTargetUserId();
6739                boolean skipCurrentProfile =
6740                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6741                boolean skipCurrentProfileIfNoMatchFound =
6742                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6743                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6744                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6745                    // Checking if there are activities in the target user that can handle the
6746                    // intent.
6747                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6748                            resolvedType, flags, sourceUserId);
6749                    if (resolveInfo != null) return resolveInfo;
6750                    alreadyTriedUserIds.put(targetUserId, true);
6751                }
6752            }
6753        }
6754        return null;
6755    }
6756
6757    /**
6758     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6759     * will forward the intent to the filter's target user.
6760     * Otherwise, returns null.
6761     */
6762    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6763            String resolvedType, int flags, int sourceUserId) {
6764        int targetUserId = filter.getTargetUserId();
6765        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6766                resolvedType, flags, targetUserId);
6767        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6768            // If all the matches in the target profile are suspended, return null.
6769            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6770                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6771                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6772                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6773                            targetUserId);
6774                }
6775            }
6776        }
6777        return null;
6778    }
6779
6780    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6781            int sourceUserId, int targetUserId) {
6782        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6783        long ident = Binder.clearCallingIdentity();
6784        boolean targetIsProfile;
6785        try {
6786            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6787        } finally {
6788            Binder.restoreCallingIdentity(ident);
6789        }
6790        String className;
6791        if (targetIsProfile) {
6792            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6793        } else {
6794            className = FORWARD_INTENT_TO_PARENT;
6795        }
6796        ComponentName forwardingActivityComponentName = new ComponentName(
6797                mAndroidApplication.packageName, className);
6798        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6799                sourceUserId);
6800        if (!targetIsProfile) {
6801            forwardingActivityInfo.showUserIcon = targetUserId;
6802            forwardingResolveInfo.noResourceId = true;
6803        }
6804        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6805        forwardingResolveInfo.priority = 0;
6806        forwardingResolveInfo.preferredOrder = 0;
6807        forwardingResolveInfo.match = 0;
6808        forwardingResolveInfo.isDefault = true;
6809        forwardingResolveInfo.filter = filter;
6810        forwardingResolveInfo.targetUserId = targetUserId;
6811        return forwardingResolveInfo;
6812    }
6813
6814    @Override
6815    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6816            Intent[] specifics, String[] specificTypes, Intent intent,
6817            String resolvedType, int flags, int userId) {
6818        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6819                specificTypes, intent, resolvedType, flags, userId));
6820    }
6821
6822    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6823            Intent[] specifics, String[] specificTypes, Intent intent,
6824            String resolvedType, int flags, int userId) {
6825        if (!sUserManager.exists(userId)) return Collections.emptyList();
6826        final int callingUid = Binder.getCallingUid();
6827        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6828                false /*includeInstantApps*/);
6829        enforceCrossUserPermission(callingUid, userId,
6830                false /*requireFullPermission*/, false /*checkShell*/,
6831                "query intent activity options");
6832        final String resultsAction = intent.getAction();
6833
6834        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6835                | PackageManager.GET_RESOLVED_FILTER, userId);
6836
6837        if (DEBUG_INTENT_MATCHING) {
6838            Log.v(TAG, "Query " + intent + ": " + results);
6839        }
6840
6841        int specificsPos = 0;
6842        int N;
6843
6844        // todo: note that the algorithm used here is O(N^2).  This
6845        // isn't a problem in our current environment, but if we start running
6846        // into situations where we have more than 5 or 10 matches then this
6847        // should probably be changed to something smarter...
6848
6849        // First we go through and resolve each of the specific items
6850        // that were supplied, taking care of removing any corresponding
6851        // duplicate items in the generic resolve list.
6852        if (specifics != null) {
6853            for (int i=0; i<specifics.length; i++) {
6854                final Intent sintent = specifics[i];
6855                if (sintent == null) {
6856                    continue;
6857                }
6858
6859                if (DEBUG_INTENT_MATCHING) {
6860                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6861                }
6862
6863                String action = sintent.getAction();
6864                if (resultsAction != null && resultsAction.equals(action)) {
6865                    // If this action was explicitly requested, then don't
6866                    // remove things that have it.
6867                    action = null;
6868                }
6869
6870                ResolveInfo ri = null;
6871                ActivityInfo ai = null;
6872
6873                ComponentName comp = sintent.getComponent();
6874                if (comp == null) {
6875                    ri = resolveIntent(
6876                        sintent,
6877                        specificTypes != null ? specificTypes[i] : null,
6878                            flags, userId);
6879                    if (ri == null) {
6880                        continue;
6881                    }
6882                    if (ri == mResolveInfo) {
6883                        // ACK!  Must do something better with this.
6884                    }
6885                    ai = ri.activityInfo;
6886                    comp = new ComponentName(ai.applicationInfo.packageName,
6887                            ai.name);
6888                } else {
6889                    ai = getActivityInfo(comp, flags, userId);
6890                    if (ai == null) {
6891                        continue;
6892                    }
6893                }
6894
6895                // Look for any generic query activities that are duplicates
6896                // of this specific one, and remove them from the results.
6897                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6898                N = results.size();
6899                int j;
6900                for (j=specificsPos; j<N; j++) {
6901                    ResolveInfo sri = results.get(j);
6902                    if ((sri.activityInfo.name.equals(comp.getClassName())
6903                            && sri.activityInfo.applicationInfo.packageName.equals(
6904                                    comp.getPackageName()))
6905                        || (action != null && sri.filter.matchAction(action))) {
6906                        results.remove(j);
6907                        if (DEBUG_INTENT_MATCHING) Log.v(
6908                            TAG, "Removing duplicate item from " + j
6909                            + " due to specific " + specificsPos);
6910                        if (ri == null) {
6911                            ri = sri;
6912                        }
6913                        j--;
6914                        N--;
6915                    }
6916                }
6917
6918                // Add this specific item to its proper place.
6919                if (ri == null) {
6920                    ri = new ResolveInfo();
6921                    ri.activityInfo = ai;
6922                }
6923                results.add(specificsPos, ri);
6924                ri.specificIndex = i;
6925                specificsPos++;
6926            }
6927        }
6928
6929        // Now we go through the remaining generic results and remove any
6930        // duplicate actions that are found here.
6931        N = results.size();
6932        for (int i=specificsPos; i<N-1; i++) {
6933            final ResolveInfo rii = results.get(i);
6934            if (rii.filter == null) {
6935                continue;
6936            }
6937
6938            // Iterate over all of the actions of this result's intent
6939            // filter...  typically this should be just one.
6940            final Iterator<String> it = rii.filter.actionsIterator();
6941            if (it == null) {
6942                continue;
6943            }
6944            while (it.hasNext()) {
6945                final String action = it.next();
6946                if (resultsAction != null && resultsAction.equals(action)) {
6947                    // If this action was explicitly requested, then don't
6948                    // remove things that have it.
6949                    continue;
6950                }
6951                for (int j=i+1; j<N; j++) {
6952                    final ResolveInfo rij = results.get(j);
6953                    if (rij.filter != null && rij.filter.hasAction(action)) {
6954                        results.remove(j);
6955                        if (DEBUG_INTENT_MATCHING) Log.v(
6956                            TAG, "Removing duplicate item from " + j
6957                            + " due to action " + action + " at " + i);
6958                        j--;
6959                        N--;
6960                    }
6961                }
6962            }
6963
6964            // If the caller didn't request filter information, drop it now
6965            // so we don't have to marshall/unmarshall it.
6966            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6967                rii.filter = null;
6968            }
6969        }
6970
6971        // Filter out the caller activity if so requested.
6972        if (caller != null) {
6973            N = results.size();
6974            for (int i=0; i<N; i++) {
6975                ActivityInfo ainfo = results.get(i).activityInfo;
6976                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6977                        && caller.getClassName().equals(ainfo.name)) {
6978                    results.remove(i);
6979                    break;
6980                }
6981            }
6982        }
6983
6984        // If the caller didn't request filter information,
6985        // drop them now so we don't have to
6986        // marshall/unmarshall it.
6987        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6988            N = results.size();
6989            for (int i=0; i<N; i++) {
6990                results.get(i).filter = null;
6991            }
6992        }
6993
6994        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6995        return results;
6996    }
6997
6998    @Override
6999    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7000            String resolvedType, int flags, int userId) {
7001        return new ParceledListSlice<>(
7002                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7003    }
7004
7005    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7006            String resolvedType, int flags, int userId) {
7007        if (!sUserManager.exists(userId)) return Collections.emptyList();
7008        final int callingUid = Binder.getCallingUid();
7009        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7010                false /*includeInstantApps*/);
7011        ComponentName comp = intent.getComponent();
7012        if (comp == null) {
7013            if (intent.getSelector() != null) {
7014                intent = intent.getSelector();
7015                comp = intent.getComponent();
7016            }
7017        }
7018        if (comp != null) {
7019            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7020            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7021            if (ai != null) {
7022                ResolveInfo ri = new ResolveInfo();
7023                ri.activityInfo = ai;
7024                list.add(ri);
7025            }
7026            return list;
7027        }
7028
7029        // reader
7030        synchronized (mPackages) {
7031            String pkgName = intent.getPackage();
7032            if (pkgName == null) {
7033                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7034            }
7035            final PackageParser.Package pkg = mPackages.get(pkgName);
7036            if (pkg != null) {
7037                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7038                        userId);
7039            }
7040            return Collections.emptyList();
7041        }
7042    }
7043
7044    @Override
7045    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7046        final int callingUid = Binder.getCallingUid();
7047        return resolveServiceInternal(
7048                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7049    }
7050
7051    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7052            int userId, int callingUid, boolean includeInstantApps) {
7053        if (!sUserManager.exists(userId)) return null;
7054        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7055        List<ResolveInfo> query = queryIntentServicesInternal(
7056                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7057        if (query != null) {
7058            if (query.size() >= 1) {
7059                // If there is more than one service with the same priority,
7060                // just arbitrarily pick the first one.
7061                return query.get(0);
7062            }
7063        }
7064        return null;
7065    }
7066
7067    @Override
7068    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7069            String resolvedType, int flags, int userId) {
7070        final int callingUid = Binder.getCallingUid();
7071        return new ParceledListSlice<>(queryIntentServicesInternal(
7072                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7073    }
7074
7075    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7076            String resolvedType, int flags, int userId, int callingUid,
7077            boolean includeInstantApps) {
7078        if (!sUserManager.exists(userId)) return Collections.emptyList();
7079        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7080        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7081        ComponentName comp = intent.getComponent();
7082        if (comp == null) {
7083            if (intent.getSelector() != null) {
7084                intent = intent.getSelector();
7085                comp = intent.getComponent();
7086            }
7087        }
7088        if (comp != null) {
7089            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7090            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7091            if (si != null) {
7092                // When specifying an explicit component, we prevent the service from being
7093                // used when either 1) the service is in an instant application and the
7094                // caller is not the same instant application or 2) the calling package is
7095                // ephemeral and the activity is not visible to ephemeral applications.
7096                final boolean matchVisibleToInstantAppOnly =
7097                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7098                final boolean isCallerInstantApp =
7099                        instantAppPkgName != null;
7100                final boolean isTargetSameInstantApp =
7101                        comp.getPackageName().equals(instantAppPkgName);
7102                final boolean isTargetHiddenFromInstantApp =
7103                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7104                final boolean blockResolution =
7105                        !isTargetSameInstantApp
7106                        && ((matchVisibleToInstantAppOnly && isCallerInstantApp
7107                                        && isTargetHiddenFromInstantApp));
7108                if (!blockResolution) {
7109                    final ResolveInfo ri = new ResolveInfo();
7110                    ri.serviceInfo = si;
7111                    list.add(ri);
7112                }
7113            }
7114            return list;
7115        }
7116
7117        // reader
7118        synchronized (mPackages) {
7119            String pkgName = intent.getPackage();
7120            if (pkgName == null) {
7121                return applyPostServiceResolutionFilter(
7122                        mServices.queryIntent(intent, resolvedType, flags, userId),
7123                        instantAppPkgName);
7124            }
7125            final PackageParser.Package pkg = mPackages.get(pkgName);
7126            if (pkg != null) {
7127                return applyPostServiceResolutionFilter(
7128                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7129                                userId),
7130                        instantAppPkgName);
7131            }
7132            return Collections.emptyList();
7133        }
7134    }
7135
7136    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7137            String instantAppPkgName) {
7138        // TODO: When adding on-demand split support for non-instant apps, remove this check
7139        // and always apply post filtering
7140        if (instantAppPkgName == null) {
7141            return resolveInfos;
7142        }
7143        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7144            final ResolveInfo info = resolveInfos.get(i);
7145            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7146            // allow services that are defined in the provided package
7147            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7148                if (info.serviceInfo.splitName != null
7149                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7150                                info.serviceInfo.splitName)) {
7151                    // requested service is defined in a split that hasn't been installed yet.
7152                    // add the installer to the resolve list
7153                    if (DEBUG_EPHEMERAL) {
7154                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7155                    }
7156                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7157                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7158                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7159                            info.serviceInfo.applicationInfo.versionCode);
7160                    // make sure this resolver is the default
7161                    installerInfo.isDefault = true;
7162                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7163                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7164                    // add a non-generic filter
7165                    installerInfo.filter = new IntentFilter();
7166                    // load resources from the correct package
7167                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7168                    resolveInfos.set(i, installerInfo);
7169                }
7170                continue;
7171            }
7172            // allow services that have been explicitly exposed to ephemeral apps
7173            if (!isEphemeralApp
7174                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7175                continue;
7176            }
7177            resolveInfos.remove(i);
7178        }
7179        return resolveInfos;
7180    }
7181
7182    @Override
7183    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7184            String resolvedType, int flags, int userId) {
7185        return new ParceledListSlice<>(
7186                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7187    }
7188
7189    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7190            Intent intent, String resolvedType, int flags, int userId) {
7191        if (!sUserManager.exists(userId)) return Collections.emptyList();
7192        final int callingUid = Binder.getCallingUid();
7193        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7194                false /*includeInstantApps*/);
7195        ComponentName comp = intent.getComponent();
7196        if (comp == null) {
7197            if (intent.getSelector() != null) {
7198                intent = intent.getSelector();
7199                comp = intent.getComponent();
7200            }
7201        }
7202        if (comp != null) {
7203            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7204            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7205            if (pi != null) {
7206                final ResolveInfo ri = new ResolveInfo();
7207                ri.providerInfo = pi;
7208                list.add(ri);
7209            }
7210            return list;
7211        }
7212
7213        // reader
7214        synchronized (mPackages) {
7215            String pkgName = intent.getPackage();
7216            if (pkgName == null) {
7217                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7218            }
7219            final PackageParser.Package pkg = mPackages.get(pkgName);
7220            if (pkg != null) {
7221                return mProviders.queryIntentForPackage(
7222                        intent, resolvedType, flags, pkg.providers, userId);
7223            }
7224            return Collections.emptyList();
7225        }
7226    }
7227
7228    @Override
7229    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7230        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7231        flags = updateFlagsForPackage(flags, userId, null);
7232        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7233        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7234                true /* requireFullPermission */, false /* checkShell */,
7235                "get installed packages");
7236
7237        // writer
7238        synchronized (mPackages) {
7239            ArrayList<PackageInfo> list;
7240            if (listUninstalled) {
7241                list = new ArrayList<>(mSettings.mPackages.size());
7242                for (PackageSetting ps : mSettings.mPackages.values()) {
7243                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7244                        continue;
7245                    }
7246                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7247                    if (pi != null) {
7248                        list.add(pi);
7249                    }
7250                }
7251            } else {
7252                list = new ArrayList<>(mPackages.size());
7253                for (PackageParser.Package p : mPackages.values()) {
7254                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7255                            Binder.getCallingUid(), userId)) {
7256                        continue;
7257                    }
7258                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7259                            p.mExtras, flags, userId);
7260                    if (pi != null) {
7261                        list.add(pi);
7262                    }
7263                }
7264            }
7265
7266            return new ParceledListSlice<>(list);
7267        }
7268    }
7269
7270    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7271            String[] permissions, boolean[] tmp, int flags, int userId) {
7272        int numMatch = 0;
7273        final PermissionsState permissionsState = ps.getPermissionsState();
7274        for (int i=0; i<permissions.length; i++) {
7275            final String permission = permissions[i];
7276            if (permissionsState.hasPermission(permission, userId)) {
7277                tmp[i] = true;
7278                numMatch++;
7279            } else {
7280                tmp[i] = false;
7281            }
7282        }
7283        if (numMatch == 0) {
7284            return;
7285        }
7286        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7287
7288        // The above might return null in cases of uninstalled apps or install-state
7289        // skew across users/profiles.
7290        if (pi != null) {
7291            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7292                if (numMatch == permissions.length) {
7293                    pi.requestedPermissions = permissions;
7294                } else {
7295                    pi.requestedPermissions = new String[numMatch];
7296                    numMatch = 0;
7297                    for (int i=0; i<permissions.length; i++) {
7298                        if (tmp[i]) {
7299                            pi.requestedPermissions[numMatch] = permissions[i];
7300                            numMatch++;
7301                        }
7302                    }
7303                }
7304            }
7305            list.add(pi);
7306        }
7307    }
7308
7309    @Override
7310    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7311            String[] permissions, int flags, int userId) {
7312        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7313        flags = updateFlagsForPackage(flags, userId, permissions);
7314        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7315                true /* requireFullPermission */, false /* checkShell */,
7316                "get packages holding permissions");
7317        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7318
7319        // writer
7320        synchronized (mPackages) {
7321            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7322            boolean[] tmpBools = new boolean[permissions.length];
7323            if (listUninstalled) {
7324                for (PackageSetting ps : mSettings.mPackages.values()) {
7325                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7326                            userId);
7327                }
7328            } else {
7329                for (PackageParser.Package pkg : mPackages.values()) {
7330                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7331                    if (ps != null) {
7332                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7333                                userId);
7334                    }
7335                }
7336            }
7337
7338            return new ParceledListSlice<PackageInfo>(list);
7339        }
7340    }
7341
7342    @Override
7343    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7344        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7345        flags = updateFlagsForApplication(flags, userId, null);
7346        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7347
7348        // writer
7349        synchronized (mPackages) {
7350            ArrayList<ApplicationInfo> list;
7351            if (listUninstalled) {
7352                list = new ArrayList<>(mSettings.mPackages.size());
7353                for (PackageSetting ps : mSettings.mPackages.values()) {
7354                    ApplicationInfo ai;
7355                    int effectiveFlags = flags;
7356                    if (ps.isSystem()) {
7357                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7358                    }
7359                    if (ps.pkg != null) {
7360                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7361                            continue;
7362                        }
7363                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7364                                ps.readUserState(userId), userId);
7365                        if (ai != null) {
7366                            rebaseEnabledOverlays(ai, userId);
7367                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7368                        }
7369                    } else {
7370                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7371                        // and already converts to externally visible package name
7372                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7373                                Binder.getCallingUid(), effectiveFlags, userId);
7374                    }
7375                    if (ai != null) {
7376                        list.add(ai);
7377                    }
7378                }
7379            } else {
7380                list = new ArrayList<>(mPackages.size());
7381                for (PackageParser.Package p : mPackages.values()) {
7382                    if (p.mExtras != null) {
7383                        PackageSetting ps = (PackageSetting) p.mExtras;
7384                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7385                            continue;
7386                        }
7387                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7388                                ps.readUserState(userId), userId);
7389                        if (ai != null) {
7390                            rebaseEnabledOverlays(ai, userId);
7391                            ai.packageName = resolveExternalPackageNameLPr(p);
7392                            list.add(ai);
7393                        }
7394                    }
7395                }
7396            }
7397
7398            return new ParceledListSlice<>(list);
7399        }
7400    }
7401
7402    @Override
7403    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7404        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7405            return null;
7406        }
7407
7408        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7409                "getEphemeralApplications");
7410        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7411                true /* requireFullPermission */, false /* checkShell */,
7412                "getEphemeralApplications");
7413        synchronized (mPackages) {
7414            List<InstantAppInfo> instantApps = mInstantAppRegistry
7415                    .getInstantAppsLPr(userId);
7416            if (instantApps != null) {
7417                return new ParceledListSlice<>(instantApps);
7418            }
7419        }
7420        return null;
7421    }
7422
7423    @Override
7424    public boolean isInstantApp(String packageName, int userId) {
7425        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7426                true /* requireFullPermission */, false /* checkShell */,
7427                "isInstantApp");
7428        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7429            return false;
7430        }
7431        int uid = Binder.getCallingUid();
7432        if (Process.isIsolated(uid)) {
7433            uid = mIsolatedOwners.get(uid);
7434        }
7435
7436        synchronized (mPackages) {
7437            final PackageSetting ps = mSettings.mPackages.get(packageName);
7438            PackageParser.Package pkg = mPackages.get(packageName);
7439            final boolean returnAllowed =
7440                    ps != null
7441                    && (isCallerSameApp(packageName, uid)
7442                            || mContext.checkCallingOrSelfPermission(
7443                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7444                                            == PERMISSION_GRANTED
7445                            || mInstantAppRegistry.isInstantAccessGranted(
7446                                    userId, UserHandle.getAppId(uid), ps.appId));
7447            if (returnAllowed) {
7448                return ps.getInstantApp(userId);
7449            }
7450        }
7451        return false;
7452    }
7453
7454    @Override
7455    public byte[] getInstantAppCookie(String packageName, int userId) {
7456        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7457            return null;
7458        }
7459
7460        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7461                true /* requireFullPermission */, false /* checkShell */,
7462                "getInstantAppCookie");
7463        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7464            return null;
7465        }
7466        synchronized (mPackages) {
7467            return mInstantAppRegistry.getInstantAppCookieLPw(
7468                    packageName, userId);
7469        }
7470    }
7471
7472    @Override
7473    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7474        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7475            return true;
7476        }
7477
7478        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7479                true /* requireFullPermission */, true /* checkShell */,
7480                "setInstantAppCookie");
7481        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7482            return false;
7483        }
7484        synchronized (mPackages) {
7485            return mInstantAppRegistry.setInstantAppCookieLPw(
7486                    packageName, cookie, userId);
7487        }
7488    }
7489
7490    @Override
7491    public Bitmap getInstantAppIcon(String packageName, int userId) {
7492        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7493            return null;
7494        }
7495
7496        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7497                "getInstantAppIcon");
7498
7499        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7500                true /* requireFullPermission */, false /* checkShell */,
7501                "getInstantAppIcon");
7502
7503        synchronized (mPackages) {
7504            return mInstantAppRegistry.getInstantAppIconLPw(
7505                    packageName, userId);
7506        }
7507    }
7508
7509    private boolean isCallerSameApp(String packageName, int uid) {
7510        PackageParser.Package pkg = mPackages.get(packageName);
7511        return pkg != null
7512                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7513    }
7514
7515    @Override
7516    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7517        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7518    }
7519
7520    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7521        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7522
7523        // reader
7524        synchronized (mPackages) {
7525            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7526            final int userId = UserHandle.getCallingUserId();
7527            while (i.hasNext()) {
7528                final PackageParser.Package p = i.next();
7529                if (p.applicationInfo == null) continue;
7530
7531                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7532                        && !p.applicationInfo.isDirectBootAware();
7533                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7534                        && p.applicationInfo.isDirectBootAware();
7535
7536                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7537                        && (!mSafeMode || isSystemApp(p))
7538                        && (matchesUnaware || matchesAware)) {
7539                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7540                    if (ps != null) {
7541                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7542                                ps.readUserState(userId), userId);
7543                        if (ai != null) {
7544                            rebaseEnabledOverlays(ai, userId);
7545                            finalList.add(ai);
7546                        }
7547                    }
7548                }
7549            }
7550        }
7551
7552        return finalList;
7553    }
7554
7555    @Override
7556    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7557        if (!sUserManager.exists(userId)) return null;
7558        flags = updateFlagsForComponent(flags, userId, name);
7559        // reader
7560        synchronized (mPackages) {
7561            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7562            PackageSetting ps = provider != null
7563                    ? mSettings.mPackages.get(provider.owner.packageName)
7564                    : null;
7565            return ps != null
7566                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7567                    ? PackageParser.generateProviderInfo(provider, flags,
7568                            ps.readUserState(userId), userId)
7569                    : null;
7570        }
7571    }
7572
7573    /**
7574     * @deprecated
7575     */
7576    @Deprecated
7577    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7578        // reader
7579        synchronized (mPackages) {
7580            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7581                    .entrySet().iterator();
7582            final int userId = UserHandle.getCallingUserId();
7583            while (i.hasNext()) {
7584                Map.Entry<String, PackageParser.Provider> entry = i.next();
7585                PackageParser.Provider p = entry.getValue();
7586                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7587
7588                if (ps != null && p.syncable
7589                        && (!mSafeMode || (p.info.applicationInfo.flags
7590                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7591                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7592                            ps.readUserState(userId), userId);
7593                    if (info != null) {
7594                        outNames.add(entry.getKey());
7595                        outInfo.add(info);
7596                    }
7597                }
7598            }
7599        }
7600    }
7601
7602    @Override
7603    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7604            int uid, int flags, String metaDataKey) {
7605        final int userId = processName != null ? UserHandle.getUserId(uid)
7606                : UserHandle.getCallingUserId();
7607        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7608        flags = updateFlagsForComponent(flags, userId, processName);
7609
7610        ArrayList<ProviderInfo> finalList = null;
7611        // reader
7612        synchronized (mPackages) {
7613            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7614            while (i.hasNext()) {
7615                final PackageParser.Provider p = i.next();
7616                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7617                if (ps != null && p.info.authority != null
7618                        && (processName == null
7619                                || (p.info.processName.equals(processName)
7620                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7621                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7622
7623                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7624                    // parameter.
7625                    if (metaDataKey != null
7626                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7627                        continue;
7628                    }
7629
7630                    if (finalList == null) {
7631                        finalList = new ArrayList<ProviderInfo>(3);
7632                    }
7633                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7634                            ps.readUserState(userId), userId);
7635                    if (info != null) {
7636                        finalList.add(info);
7637                    }
7638                }
7639            }
7640        }
7641
7642        if (finalList != null) {
7643            Collections.sort(finalList, mProviderInitOrderSorter);
7644            return new ParceledListSlice<ProviderInfo>(finalList);
7645        }
7646
7647        return ParceledListSlice.emptyList();
7648    }
7649
7650    @Override
7651    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7652        // reader
7653        synchronized (mPackages) {
7654            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7655            return PackageParser.generateInstrumentationInfo(i, flags);
7656        }
7657    }
7658
7659    @Override
7660    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7661            String targetPackage, int flags) {
7662        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7663    }
7664
7665    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7666            int flags) {
7667        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7668
7669        // reader
7670        synchronized (mPackages) {
7671            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7672            while (i.hasNext()) {
7673                final PackageParser.Instrumentation p = i.next();
7674                if (targetPackage == null
7675                        || targetPackage.equals(p.info.targetPackage)) {
7676                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7677                            flags);
7678                    if (ii != null) {
7679                        finalList.add(ii);
7680                    }
7681                }
7682            }
7683        }
7684
7685        return finalList;
7686    }
7687
7688    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7689        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7690        try {
7691            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7692        } finally {
7693            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7694        }
7695    }
7696
7697    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7698        final File[] files = dir.listFiles();
7699        if (ArrayUtils.isEmpty(files)) {
7700            Log.d(TAG, "No files in app dir " + dir);
7701            return;
7702        }
7703
7704        if (DEBUG_PACKAGE_SCANNING) {
7705            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7706                    + " flags=0x" + Integer.toHexString(parseFlags));
7707        }
7708        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7709                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7710
7711        // Submit files for parsing in parallel
7712        int fileCount = 0;
7713        for (File file : files) {
7714            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7715                    && !PackageInstallerService.isStageName(file.getName());
7716            if (!isPackage) {
7717                // Ignore entries which are not packages
7718                continue;
7719            }
7720            parallelPackageParser.submit(file, parseFlags);
7721            fileCount++;
7722        }
7723
7724        // Process results one by one
7725        for (; fileCount > 0; fileCount--) {
7726            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7727            Throwable throwable = parseResult.throwable;
7728            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7729
7730            if (throwable == null) {
7731                // Static shared libraries have synthetic package names
7732                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7733                    renameStaticSharedLibraryPackage(parseResult.pkg);
7734                }
7735                try {
7736                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7737                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7738                                currentTime, null);
7739                    }
7740                } catch (PackageManagerException e) {
7741                    errorCode = e.error;
7742                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7743                }
7744            } else if (throwable instanceof PackageParser.PackageParserException) {
7745                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7746                        throwable;
7747                errorCode = e.error;
7748                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7749            } else {
7750                throw new IllegalStateException("Unexpected exception occurred while parsing "
7751                        + parseResult.scanFile, throwable);
7752            }
7753
7754            // Delete invalid userdata apps
7755            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7756                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7757                logCriticalInfo(Log.WARN,
7758                        "Deleting invalid package at " + parseResult.scanFile);
7759                removeCodePathLI(parseResult.scanFile);
7760            }
7761        }
7762        parallelPackageParser.close();
7763    }
7764
7765    private static File getSettingsProblemFile() {
7766        File dataDir = Environment.getDataDirectory();
7767        File systemDir = new File(dataDir, "system");
7768        File fname = new File(systemDir, "uiderrors.txt");
7769        return fname;
7770    }
7771
7772    static void reportSettingsProblem(int priority, String msg) {
7773        logCriticalInfo(priority, msg);
7774    }
7775
7776    public static void logCriticalInfo(int priority, String msg) {
7777        Slog.println(priority, TAG, msg);
7778        EventLogTags.writePmCriticalInfo(msg);
7779        try {
7780            File fname = getSettingsProblemFile();
7781            FileOutputStream out = new FileOutputStream(fname, true);
7782            PrintWriter pw = new FastPrintWriter(out);
7783            SimpleDateFormat formatter = new SimpleDateFormat();
7784            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7785            pw.println(dateString + ": " + msg);
7786            pw.close();
7787            FileUtils.setPermissions(
7788                    fname.toString(),
7789                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7790                    -1, -1);
7791        } catch (java.io.IOException e) {
7792        }
7793    }
7794
7795    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7796        if (srcFile.isDirectory()) {
7797            final File baseFile = new File(pkg.baseCodePath);
7798            long maxModifiedTime = baseFile.lastModified();
7799            if (pkg.splitCodePaths != null) {
7800                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7801                    final File splitFile = new File(pkg.splitCodePaths[i]);
7802                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7803                }
7804            }
7805            return maxModifiedTime;
7806        }
7807        return srcFile.lastModified();
7808    }
7809
7810    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7811            final int policyFlags) throws PackageManagerException {
7812        // When upgrading from pre-N MR1, verify the package time stamp using the package
7813        // directory and not the APK file.
7814        final long lastModifiedTime = mIsPreNMR1Upgrade
7815                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7816        if (ps != null
7817                && ps.codePath.equals(srcFile)
7818                && ps.timeStamp == lastModifiedTime
7819                && !isCompatSignatureUpdateNeeded(pkg)
7820                && !isRecoverSignatureUpdateNeeded(pkg)) {
7821            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7822            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7823            ArraySet<PublicKey> signingKs;
7824            synchronized (mPackages) {
7825                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7826            }
7827            if (ps.signatures.mSignatures != null
7828                    && ps.signatures.mSignatures.length != 0
7829                    && signingKs != null) {
7830                // Optimization: reuse the existing cached certificates
7831                // if the package appears to be unchanged.
7832                pkg.mSignatures = ps.signatures.mSignatures;
7833                pkg.mSigningKeys = signingKs;
7834                return;
7835            }
7836
7837            Slog.w(TAG, "PackageSetting for " + ps.name
7838                    + " is missing signatures.  Collecting certs again to recover them.");
7839        } else {
7840            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7841        }
7842
7843        try {
7844            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7845            PackageParser.collectCertificates(pkg, policyFlags);
7846        } catch (PackageParserException e) {
7847            throw PackageManagerException.from(e);
7848        } finally {
7849            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7850        }
7851    }
7852
7853    /**
7854     *  Traces a package scan.
7855     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7856     */
7857    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7858            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7859        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7860        try {
7861            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7862        } finally {
7863            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7864        }
7865    }
7866
7867    /**
7868     *  Scans a package and returns the newly parsed package.
7869     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7870     */
7871    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7872            long currentTime, UserHandle user) throws PackageManagerException {
7873        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7874        PackageParser pp = new PackageParser();
7875        pp.setSeparateProcesses(mSeparateProcesses);
7876        pp.setOnlyCoreApps(mOnlyCore);
7877        pp.setDisplayMetrics(mMetrics);
7878        pp.setCallback(mPackageParserCallback);
7879
7880        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7881            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7882        }
7883
7884        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7885        final PackageParser.Package pkg;
7886        try {
7887            pkg = pp.parsePackage(scanFile, parseFlags);
7888        } catch (PackageParserException e) {
7889            throw PackageManagerException.from(e);
7890        } finally {
7891            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7892        }
7893
7894        // Static shared libraries have synthetic package names
7895        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7896            renameStaticSharedLibraryPackage(pkg);
7897        }
7898
7899        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7900    }
7901
7902    /**
7903     *  Scans a package and returns the newly parsed package.
7904     *  @throws PackageManagerException on a parse error.
7905     */
7906    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7907            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7908            throws PackageManagerException {
7909        // If the package has children and this is the first dive in the function
7910        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7911        // packages (parent and children) would be successfully scanned before the
7912        // actual scan since scanning mutates internal state and we want to atomically
7913        // install the package and its children.
7914        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7915            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7916                scanFlags |= SCAN_CHECK_ONLY;
7917            }
7918        } else {
7919            scanFlags &= ~SCAN_CHECK_ONLY;
7920        }
7921
7922        // Scan the parent
7923        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7924                scanFlags, currentTime, user);
7925
7926        // Scan the children
7927        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7928        for (int i = 0; i < childCount; i++) {
7929            PackageParser.Package childPackage = pkg.childPackages.get(i);
7930            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7931                    currentTime, user);
7932        }
7933
7934
7935        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7936            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7937        }
7938
7939        return scannedPkg;
7940    }
7941
7942    /**
7943     *  Scans a package and returns the newly parsed package.
7944     *  @throws PackageManagerException on a parse error.
7945     */
7946    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7947            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7948            throws PackageManagerException {
7949        PackageSetting ps = null;
7950        PackageSetting updatedPkg;
7951        // reader
7952        synchronized (mPackages) {
7953            // Look to see if we already know about this package.
7954            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7955            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7956                // This package has been renamed to its original name.  Let's
7957                // use that.
7958                ps = mSettings.getPackageLPr(oldName);
7959            }
7960            // If there was no original package, see one for the real package name.
7961            if (ps == null) {
7962                ps = mSettings.getPackageLPr(pkg.packageName);
7963            }
7964            // Check to see if this package could be hiding/updating a system
7965            // package.  Must look for it either under the original or real
7966            // package name depending on our state.
7967            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7968            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7969
7970            // If this is a package we don't know about on the system partition, we
7971            // may need to remove disabled child packages on the system partition
7972            // or may need to not add child packages if the parent apk is updated
7973            // on the data partition and no longer defines this child package.
7974            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7975                // If this is a parent package for an updated system app and this system
7976                // app got an OTA update which no longer defines some of the child packages
7977                // we have to prune them from the disabled system packages.
7978                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7979                if (disabledPs != null) {
7980                    final int scannedChildCount = (pkg.childPackages != null)
7981                            ? pkg.childPackages.size() : 0;
7982                    final int disabledChildCount = disabledPs.childPackageNames != null
7983                            ? disabledPs.childPackageNames.size() : 0;
7984                    for (int i = 0; i < disabledChildCount; i++) {
7985                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7986                        boolean disabledPackageAvailable = false;
7987                        for (int j = 0; j < scannedChildCount; j++) {
7988                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7989                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7990                                disabledPackageAvailable = true;
7991                                break;
7992                            }
7993                         }
7994                         if (!disabledPackageAvailable) {
7995                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7996                         }
7997                    }
7998                }
7999            }
8000        }
8001
8002        boolean updatedPkgBetter = false;
8003        // First check if this is a system package that may involve an update
8004        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8005            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8006            // it needs to drop FLAG_PRIVILEGED.
8007            if (locationIsPrivileged(scanFile)) {
8008                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8009            } else {
8010                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8011            }
8012
8013            if (ps != null && !ps.codePath.equals(scanFile)) {
8014                // The path has changed from what was last scanned...  check the
8015                // version of the new path against what we have stored to determine
8016                // what to do.
8017                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8018                if (pkg.mVersionCode <= ps.versionCode) {
8019                    // The system package has been updated and the code path does not match
8020                    // Ignore entry. Skip it.
8021                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8022                            + " ignored: updated version " + ps.versionCode
8023                            + " better than this " + pkg.mVersionCode);
8024                    if (!updatedPkg.codePath.equals(scanFile)) {
8025                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8026                                + ps.name + " changing from " + updatedPkg.codePathString
8027                                + " to " + scanFile);
8028                        updatedPkg.codePath = scanFile;
8029                        updatedPkg.codePathString = scanFile.toString();
8030                        updatedPkg.resourcePath = scanFile;
8031                        updatedPkg.resourcePathString = scanFile.toString();
8032                    }
8033                    updatedPkg.pkg = pkg;
8034                    updatedPkg.versionCode = pkg.mVersionCode;
8035
8036                    // Update the disabled system child packages to point to the package too.
8037                    final int childCount = updatedPkg.childPackageNames != null
8038                            ? updatedPkg.childPackageNames.size() : 0;
8039                    for (int i = 0; i < childCount; i++) {
8040                        String childPackageName = updatedPkg.childPackageNames.get(i);
8041                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8042                                childPackageName);
8043                        if (updatedChildPkg != null) {
8044                            updatedChildPkg.pkg = pkg;
8045                            updatedChildPkg.versionCode = pkg.mVersionCode;
8046                        }
8047                    }
8048
8049                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8050                            + scanFile + " ignored: updated version " + ps.versionCode
8051                            + " better than this " + pkg.mVersionCode);
8052                } else {
8053                    // The current app on the system partition is better than
8054                    // what we have updated to on the data partition; switch
8055                    // back to the system partition version.
8056                    // At this point, its safely assumed that package installation for
8057                    // apps in system partition will go through. If not there won't be a working
8058                    // version of the app
8059                    // writer
8060                    synchronized (mPackages) {
8061                        // Just remove the loaded entries from package lists.
8062                        mPackages.remove(ps.name);
8063                    }
8064
8065                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8066                            + " reverting from " + ps.codePathString
8067                            + ": new version " + pkg.mVersionCode
8068                            + " better than installed " + ps.versionCode);
8069
8070                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8071                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8072                    synchronized (mInstallLock) {
8073                        args.cleanUpResourcesLI();
8074                    }
8075                    synchronized (mPackages) {
8076                        mSettings.enableSystemPackageLPw(ps.name);
8077                    }
8078                    updatedPkgBetter = true;
8079                }
8080            }
8081        }
8082
8083        if (updatedPkg != null) {
8084            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8085            // initially
8086            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8087
8088            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8089            // flag set initially
8090            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8091                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8092            }
8093        }
8094
8095        // Verify certificates against what was last scanned
8096        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8097
8098        /*
8099         * A new system app appeared, but we already had a non-system one of the
8100         * same name installed earlier.
8101         */
8102        boolean shouldHideSystemApp = false;
8103        if (updatedPkg == null && ps != null
8104                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8105            /*
8106             * Check to make sure the signatures match first. If they don't,
8107             * wipe the installed application and its data.
8108             */
8109            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8110                    != PackageManager.SIGNATURE_MATCH) {
8111                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8112                        + " signatures don't match existing userdata copy; removing");
8113                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8114                        "scanPackageInternalLI")) {
8115                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8116                }
8117                ps = null;
8118            } else {
8119                /*
8120                 * If the newly-added system app is an older version than the
8121                 * already installed version, hide it. It will be scanned later
8122                 * and re-added like an update.
8123                 */
8124                if (pkg.mVersionCode <= ps.versionCode) {
8125                    shouldHideSystemApp = true;
8126                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8127                            + " but new version " + pkg.mVersionCode + " better than installed "
8128                            + ps.versionCode + "; hiding system");
8129                } else {
8130                    /*
8131                     * The newly found system app is a newer version that the
8132                     * one previously installed. Simply remove the
8133                     * already-installed application and replace it with our own
8134                     * while keeping the application data.
8135                     */
8136                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8137                            + " reverting from " + ps.codePathString + ": new version "
8138                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8139                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8140                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8141                    synchronized (mInstallLock) {
8142                        args.cleanUpResourcesLI();
8143                    }
8144                }
8145            }
8146        }
8147
8148        // The apk is forward locked (not public) if its code and resources
8149        // are kept in different files. (except for app in either system or
8150        // vendor path).
8151        // TODO grab this value from PackageSettings
8152        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8153            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8154                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8155            }
8156        }
8157
8158        // TODO: extend to support forward-locked splits
8159        String resourcePath = null;
8160        String baseResourcePath = null;
8161        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8162            if (ps != null && ps.resourcePathString != null) {
8163                resourcePath = ps.resourcePathString;
8164                baseResourcePath = ps.resourcePathString;
8165            } else {
8166                // Should not happen at all. Just log an error.
8167                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8168            }
8169        } else {
8170            resourcePath = pkg.codePath;
8171            baseResourcePath = pkg.baseCodePath;
8172        }
8173
8174        // Set application objects path explicitly.
8175        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8176        pkg.setApplicationInfoCodePath(pkg.codePath);
8177        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8178        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8179        pkg.setApplicationInfoResourcePath(resourcePath);
8180        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8181        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8182
8183        final int userId = ((user == null) ? 0 : user.getIdentifier());
8184        if (ps != null && ps.getInstantApp(userId)) {
8185            scanFlags |= SCAN_AS_INSTANT_APP;
8186        }
8187
8188        // Note that we invoke the following method only if we are about to unpack an application
8189        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8190                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8191
8192        /*
8193         * If the system app should be overridden by a previously installed
8194         * data, hide the system app now and let the /data/app scan pick it up
8195         * again.
8196         */
8197        if (shouldHideSystemApp) {
8198            synchronized (mPackages) {
8199                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8200            }
8201        }
8202
8203        return scannedPkg;
8204    }
8205
8206    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8207        // Derive the new package synthetic package name
8208        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8209                + pkg.staticSharedLibVersion);
8210    }
8211
8212    private static String fixProcessName(String defProcessName,
8213            String processName) {
8214        if (processName == null) {
8215            return defProcessName;
8216        }
8217        return processName;
8218    }
8219
8220    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8221            throws PackageManagerException {
8222        if (pkgSetting.signatures.mSignatures != null) {
8223            // Already existing package. Make sure signatures match
8224            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8225                    == PackageManager.SIGNATURE_MATCH;
8226            if (!match) {
8227                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8228                        == PackageManager.SIGNATURE_MATCH;
8229            }
8230            if (!match) {
8231                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8232                        == PackageManager.SIGNATURE_MATCH;
8233            }
8234            if (!match) {
8235                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8236                        + pkg.packageName + " signatures do not match the "
8237                        + "previously installed version; ignoring!");
8238            }
8239        }
8240
8241        // Check for shared user signatures
8242        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8243            // Already existing package. Make sure signatures match
8244            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8245                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8246            if (!match) {
8247                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8248                        == PackageManager.SIGNATURE_MATCH;
8249            }
8250            if (!match) {
8251                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8252                        == PackageManager.SIGNATURE_MATCH;
8253            }
8254            if (!match) {
8255                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8256                        "Package " + pkg.packageName
8257                        + " has no signatures that match those in shared user "
8258                        + pkgSetting.sharedUser.name + "; ignoring!");
8259            }
8260        }
8261    }
8262
8263    /**
8264     * Enforces that only the system UID or root's UID can call a method exposed
8265     * via Binder.
8266     *
8267     * @param message used as message if SecurityException is thrown
8268     * @throws SecurityException if the caller is not system or root
8269     */
8270    private static final void enforceSystemOrRoot(String message) {
8271        final int uid = Binder.getCallingUid();
8272        if (uid != Process.SYSTEM_UID && uid != 0) {
8273            throw new SecurityException(message);
8274        }
8275    }
8276
8277    @Override
8278    public void performFstrimIfNeeded() {
8279        enforceSystemOrRoot("Only the system can request fstrim");
8280
8281        // Before everything else, see whether we need to fstrim.
8282        try {
8283            IStorageManager sm = PackageHelper.getStorageManager();
8284            if (sm != null) {
8285                boolean doTrim = false;
8286                final long interval = android.provider.Settings.Global.getLong(
8287                        mContext.getContentResolver(),
8288                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8289                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8290                if (interval > 0) {
8291                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8292                    if (timeSinceLast > interval) {
8293                        doTrim = true;
8294                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8295                                + "; running immediately");
8296                    }
8297                }
8298                if (doTrim) {
8299                    final boolean dexOptDialogShown;
8300                    synchronized (mPackages) {
8301                        dexOptDialogShown = mDexOptDialogShown;
8302                    }
8303                    if (!isFirstBoot() && dexOptDialogShown) {
8304                        try {
8305                            ActivityManager.getService().showBootMessage(
8306                                    mContext.getResources().getString(
8307                                            R.string.android_upgrading_fstrim), true);
8308                        } catch (RemoteException e) {
8309                        }
8310                    }
8311                    sm.runMaintenance();
8312                }
8313            } else {
8314                Slog.e(TAG, "storageManager service unavailable!");
8315            }
8316        } catch (RemoteException e) {
8317            // Can't happen; StorageManagerService is local
8318        }
8319    }
8320
8321    @Override
8322    public void updatePackagesIfNeeded() {
8323        enforceSystemOrRoot("Only the system can request package update");
8324
8325        // We need to re-extract after an OTA.
8326        boolean causeUpgrade = isUpgrade();
8327
8328        // First boot or factory reset.
8329        // Note: we also handle devices that are upgrading to N right now as if it is their
8330        //       first boot, as they do not have profile data.
8331        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8332
8333        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8334        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8335
8336        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8337            return;
8338        }
8339
8340        List<PackageParser.Package> pkgs;
8341        synchronized (mPackages) {
8342            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8343        }
8344
8345        final long startTime = System.nanoTime();
8346        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8347                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8348
8349        final int elapsedTimeSeconds =
8350                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8351
8352        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8353        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8354        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8355        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8356        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8357    }
8358
8359    /**
8360     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8361     * containing statistics about the invocation. The array consists of three elements,
8362     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8363     * and {@code numberOfPackagesFailed}.
8364     */
8365    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8366            String compilerFilter) {
8367
8368        int numberOfPackagesVisited = 0;
8369        int numberOfPackagesOptimized = 0;
8370        int numberOfPackagesSkipped = 0;
8371        int numberOfPackagesFailed = 0;
8372        final int numberOfPackagesToDexopt = pkgs.size();
8373
8374        for (PackageParser.Package pkg : pkgs) {
8375            numberOfPackagesVisited++;
8376
8377            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8378                if (DEBUG_DEXOPT) {
8379                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8380                }
8381                numberOfPackagesSkipped++;
8382                continue;
8383            }
8384
8385            if (DEBUG_DEXOPT) {
8386                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8387                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8388            }
8389
8390            if (showDialog) {
8391                try {
8392                    ActivityManager.getService().showBootMessage(
8393                            mContext.getResources().getString(R.string.android_upgrading_apk,
8394                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8395                } catch (RemoteException e) {
8396                }
8397                synchronized (mPackages) {
8398                    mDexOptDialogShown = true;
8399                }
8400            }
8401
8402            // If the OTA updates a system app which was previously preopted to a non-preopted state
8403            // the app might end up being verified at runtime. That's because by default the apps
8404            // are verify-profile but for preopted apps there's no profile.
8405            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8406            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8407            // filter (by default interpret-only).
8408            // Note that at this stage unused apps are already filtered.
8409            if (isSystemApp(pkg) &&
8410                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8411                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8412                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8413            }
8414
8415            // checkProfiles is false to avoid merging profiles during boot which
8416            // might interfere with background compilation (b/28612421).
8417            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8418            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8419            // trade-off worth doing to save boot time work.
8420            int dexOptStatus = performDexOptTraced(pkg.packageName,
8421                    false /* checkProfiles */,
8422                    compilerFilter,
8423                    false /* force */);
8424            switch (dexOptStatus) {
8425                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8426                    numberOfPackagesOptimized++;
8427                    break;
8428                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8429                    numberOfPackagesSkipped++;
8430                    break;
8431                case PackageDexOptimizer.DEX_OPT_FAILED:
8432                    numberOfPackagesFailed++;
8433                    break;
8434                default:
8435                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8436                    break;
8437            }
8438        }
8439
8440        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8441                numberOfPackagesFailed };
8442    }
8443
8444    @Override
8445    public void notifyPackageUse(String packageName, int reason) {
8446        synchronized (mPackages) {
8447            PackageParser.Package p = mPackages.get(packageName);
8448            if (p == null) {
8449                return;
8450            }
8451            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8452        }
8453    }
8454
8455    @Override
8456    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8457        int userId = UserHandle.getCallingUserId();
8458        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8459        if (ai == null) {
8460            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8461                + loadingPackageName + ", user=" + userId);
8462            return;
8463        }
8464        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8465    }
8466
8467    // TODO: this is not used nor needed. Delete it.
8468    @Override
8469    public boolean performDexOptIfNeeded(String packageName) {
8470        int dexOptStatus = performDexOptTraced(packageName,
8471                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8472        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8473    }
8474
8475    @Override
8476    public boolean performDexOpt(String packageName,
8477            boolean checkProfiles, int compileReason, boolean force) {
8478        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8479                getCompilerFilterForReason(compileReason), force);
8480        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8481    }
8482
8483    @Override
8484    public boolean performDexOptMode(String packageName,
8485            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8486        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8487                targetCompilerFilter, force);
8488        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8489    }
8490
8491    private int performDexOptTraced(String packageName,
8492                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8493        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8494        try {
8495            return performDexOptInternal(packageName, checkProfiles,
8496                    targetCompilerFilter, force);
8497        } finally {
8498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8499        }
8500    }
8501
8502    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8503    // if the package can now be considered up to date for the given filter.
8504    private int performDexOptInternal(String packageName,
8505                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8506        PackageParser.Package p;
8507        synchronized (mPackages) {
8508            p = mPackages.get(packageName);
8509            if (p == null) {
8510                // Package could not be found. Report failure.
8511                return PackageDexOptimizer.DEX_OPT_FAILED;
8512            }
8513            mPackageUsage.maybeWriteAsync(mPackages);
8514            mCompilerStats.maybeWriteAsync();
8515        }
8516        long callingId = Binder.clearCallingIdentity();
8517        try {
8518            synchronized (mInstallLock) {
8519                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8520                        targetCompilerFilter, force);
8521            }
8522        } finally {
8523            Binder.restoreCallingIdentity(callingId);
8524        }
8525    }
8526
8527    public ArraySet<String> getOptimizablePackages() {
8528        ArraySet<String> pkgs = new ArraySet<String>();
8529        synchronized (mPackages) {
8530            for (PackageParser.Package p : mPackages.values()) {
8531                if (PackageDexOptimizer.canOptimizePackage(p)) {
8532                    pkgs.add(p.packageName);
8533                }
8534            }
8535        }
8536        return pkgs;
8537    }
8538
8539    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8540            boolean checkProfiles, String targetCompilerFilter,
8541            boolean force) {
8542        // Select the dex optimizer based on the force parameter.
8543        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8544        //       allocate an object here.
8545        PackageDexOptimizer pdo = force
8546                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8547                : mPackageDexOptimizer;
8548
8549        // Dexopt all dependencies first. Note: we ignore the return value and march on
8550        // on errors.
8551        // Note that we are going to call performDexOpt on those libraries as many times as
8552        // they are referenced in packages. When we do a batch of performDexOpt (for example
8553        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8554        // and the first package that uses the library will dexopt it. The
8555        // others will see that the compiled code for the library is up to date.
8556        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8557        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8558        if (!deps.isEmpty()) {
8559            for (PackageParser.Package depPackage : deps) {
8560                // TODO: Analyze and investigate if we (should) profile libraries.
8561                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8562                        false /* checkProfiles */,
8563                        targetCompilerFilter,
8564                        getOrCreateCompilerPackageStats(depPackage),
8565                        true /* isUsedByOtherApps */);
8566            }
8567        }
8568        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8569                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8570                mDexManager.isUsedByOtherApps(p.packageName));
8571    }
8572
8573    // Performs dexopt on the used secondary dex files belonging to the given package.
8574    // Returns true if all dex files were process successfully (which could mean either dexopt or
8575    // skip). Returns false if any of the files caused errors.
8576    @Override
8577    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8578            boolean force) {
8579        mDexManager.reconcileSecondaryDexFiles(packageName);
8580        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8581    }
8582
8583    public boolean performDexOptSecondary(String packageName, int compileReason,
8584            boolean force) {
8585        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8586    }
8587
8588    /**
8589     * Reconcile the information we have about the secondary dex files belonging to
8590     * {@code packagName} and the actual dex files. For all dex files that were
8591     * deleted, update the internal records and delete the generated oat files.
8592     */
8593    @Override
8594    public void reconcileSecondaryDexFiles(String packageName) {
8595        mDexManager.reconcileSecondaryDexFiles(packageName);
8596    }
8597
8598    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8599    // a reference there.
8600    /*package*/ DexManager getDexManager() {
8601        return mDexManager;
8602    }
8603
8604    /**
8605     * Execute the background dexopt job immediately.
8606     */
8607    @Override
8608    public boolean runBackgroundDexoptJob() {
8609        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8610    }
8611
8612    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8613        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8614                || p.usesStaticLibraries != null) {
8615            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8616            Set<String> collectedNames = new HashSet<>();
8617            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8618
8619            retValue.remove(p);
8620
8621            return retValue;
8622        } else {
8623            return Collections.emptyList();
8624        }
8625    }
8626
8627    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8628            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8629        if (!collectedNames.contains(p.packageName)) {
8630            collectedNames.add(p.packageName);
8631            collected.add(p);
8632
8633            if (p.usesLibraries != null) {
8634                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8635                        null, collected, collectedNames);
8636            }
8637            if (p.usesOptionalLibraries != null) {
8638                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8639                        null, collected, collectedNames);
8640            }
8641            if (p.usesStaticLibraries != null) {
8642                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8643                        p.usesStaticLibrariesVersions, collected, collectedNames);
8644            }
8645        }
8646    }
8647
8648    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8649            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8650        final int libNameCount = libs.size();
8651        for (int i = 0; i < libNameCount; i++) {
8652            String libName = libs.get(i);
8653            int version = (versions != null && versions.length == libNameCount)
8654                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8655            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8656            if (libPkg != null) {
8657                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8658            }
8659        }
8660    }
8661
8662    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8663        synchronized (mPackages) {
8664            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8665            if (libEntry != null) {
8666                return mPackages.get(libEntry.apk);
8667            }
8668            return null;
8669        }
8670    }
8671
8672    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8673        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8674        if (versionedLib == null) {
8675            return null;
8676        }
8677        return versionedLib.get(version);
8678    }
8679
8680    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8681        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8682                pkg.staticSharedLibName);
8683        if (versionedLib == null) {
8684            return null;
8685        }
8686        int previousLibVersion = -1;
8687        final int versionCount = versionedLib.size();
8688        for (int i = 0; i < versionCount; i++) {
8689            final int libVersion = versionedLib.keyAt(i);
8690            if (libVersion < pkg.staticSharedLibVersion) {
8691                previousLibVersion = Math.max(previousLibVersion, libVersion);
8692            }
8693        }
8694        if (previousLibVersion >= 0) {
8695            return versionedLib.get(previousLibVersion);
8696        }
8697        return null;
8698    }
8699
8700    public void shutdown() {
8701        mPackageUsage.writeNow(mPackages);
8702        mCompilerStats.writeNow();
8703    }
8704
8705    @Override
8706    public void dumpProfiles(String packageName) {
8707        PackageParser.Package pkg;
8708        synchronized (mPackages) {
8709            pkg = mPackages.get(packageName);
8710            if (pkg == null) {
8711                throw new IllegalArgumentException("Unknown package: " + packageName);
8712            }
8713        }
8714        /* Only the shell, root, or the app user should be able to dump profiles. */
8715        int callingUid = Binder.getCallingUid();
8716        if (callingUid != Process.SHELL_UID &&
8717            callingUid != Process.ROOT_UID &&
8718            callingUid != pkg.applicationInfo.uid) {
8719            throw new SecurityException("dumpProfiles");
8720        }
8721
8722        synchronized (mInstallLock) {
8723            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8724            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8725            try {
8726                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8727                String codePaths = TextUtils.join(";", allCodePaths);
8728                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8729            } catch (InstallerException e) {
8730                Slog.w(TAG, "Failed to dump profiles", e);
8731            }
8732            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8733        }
8734    }
8735
8736    @Override
8737    public void forceDexOpt(String packageName) {
8738        enforceSystemOrRoot("forceDexOpt");
8739
8740        PackageParser.Package pkg;
8741        synchronized (mPackages) {
8742            pkg = mPackages.get(packageName);
8743            if (pkg == null) {
8744                throw new IllegalArgumentException("Unknown package: " + packageName);
8745            }
8746        }
8747
8748        synchronized (mInstallLock) {
8749            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8750
8751            // Whoever is calling forceDexOpt wants a fully compiled package.
8752            // Don't use profiles since that may cause compilation to be skipped.
8753            final int res = performDexOptInternalWithDependenciesLI(pkg,
8754                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8755                    true /* force */);
8756
8757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8758            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8759                throw new IllegalStateException("Failed to dexopt: " + res);
8760            }
8761        }
8762    }
8763
8764    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8765        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8766            Slog.w(TAG, "Unable to update from " + oldPkg.name
8767                    + " to " + newPkg.packageName
8768                    + ": old package not in system partition");
8769            return false;
8770        } else if (mPackages.get(oldPkg.name) != null) {
8771            Slog.w(TAG, "Unable to update from " + oldPkg.name
8772                    + " to " + newPkg.packageName
8773                    + ": old package still exists");
8774            return false;
8775        }
8776        return true;
8777    }
8778
8779    void removeCodePathLI(File codePath) {
8780        if (codePath.isDirectory()) {
8781            try {
8782                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8783            } catch (InstallerException e) {
8784                Slog.w(TAG, "Failed to remove code path", e);
8785            }
8786        } else {
8787            codePath.delete();
8788        }
8789    }
8790
8791    private int[] resolveUserIds(int userId) {
8792        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8793    }
8794
8795    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8796        if (pkg == null) {
8797            Slog.wtf(TAG, "Package was null!", new Throwable());
8798            return;
8799        }
8800        clearAppDataLeafLIF(pkg, userId, flags);
8801        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8802        for (int i = 0; i < childCount; i++) {
8803            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8804        }
8805    }
8806
8807    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8808        final PackageSetting ps;
8809        synchronized (mPackages) {
8810            ps = mSettings.mPackages.get(pkg.packageName);
8811        }
8812        for (int realUserId : resolveUserIds(userId)) {
8813            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8814            try {
8815                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8816                        ceDataInode);
8817            } catch (InstallerException e) {
8818                Slog.w(TAG, String.valueOf(e));
8819            }
8820        }
8821    }
8822
8823    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8824        if (pkg == null) {
8825            Slog.wtf(TAG, "Package was null!", new Throwable());
8826            return;
8827        }
8828        destroyAppDataLeafLIF(pkg, userId, flags);
8829        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8830        for (int i = 0; i < childCount; i++) {
8831            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8832        }
8833    }
8834
8835    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8836        final PackageSetting ps;
8837        synchronized (mPackages) {
8838            ps = mSettings.mPackages.get(pkg.packageName);
8839        }
8840        for (int realUserId : resolveUserIds(userId)) {
8841            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8842            try {
8843                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8844                        ceDataInode);
8845            } catch (InstallerException e) {
8846                Slog.w(TAG, String.valueOf(e));
8847            }
8848            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8849        }
8850    }
8851
8852    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8853        if (pkg == null) {
8854            Slog.wtf(TAG, "Package was null!", new Throwable());
8855            return;
8856        }
8857        destroyAppProfilesLeafLIF(pkg);
8858        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8859        for (int i = 0; i < childCount; i++) {
8860            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8861        }
8862    }
8863
8864    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8865        try {
8866            mInstaller.destroyAppProfiles(pkg.packageName);
8867        } catch (InstallerException e) {
8868            Slog.w(TAG, String.valueOf(e));
8869        }
8870    }
8871
8872    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8873        if (pkg == null) {
8874            Slog.wtf(TAG, "Package was null!", new Throwable());
8875            return;
8876        }
8877        clearAppProfilesLeafLIF(pkg);
8878        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8879        for (int i = 0; i < childCount; i++) {
8880            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8881        }
8882    }
8883
8884    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8885        try {
8886            mInstaller.clearAppProfiles(pkg.packageName);
8887        } catch (InstallerException e) {
8888            Slog.w(TAG, String.valueOf(e));
8889        }
8890    }
8891
8892    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8893            long lastUpdateTime) {
8894        // Set parent install/update time
8895        PackageSetting ps = (PackageSetting) pkg.mExtras;
8896        if (ps != null) {
8897            ps.firstInstallTime = firstInstallTime;
8898            ps.lastUpdateTime = lastUpdateTime;
8899        }
8900        // Set children install/update time
8901        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8902        for (int i = 0; i < childCount; i++) {
8903            PackageParser.Package childPkg = pkg.childPackages.get(i);
8904            ps = (PackageSetting) childPkg.mExtras;
8905            if (ps != null) {
8906                ps.firstInstallTime = firstInstallTime;
8907                ps.lastUpdateTime = lastUpdateTime;
8908            }
8909        }
8910    }
8911
8912    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8913            PackageParser.Package changingLib) {
8914        if (file.path != null) {
8915            usesLibraryFiles.add(file.path);
8916            return;
8917        }
8918        PackageParser.Package p = mPackages.get(file.apk);
8919        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8920            // If we are doing this while in the middle of updating a library apk,
8921            // then we need to make sure to use that new apk for determining the
8922            // dependencies here.  (We haven't yet finished committing the new apk
8923            // to the package manager state.)
8924            if (p == null || p.packageName.equals(changingLib.packageName)) {
8925                p = changingLib;
8926            }
8927        }
8928        if (p != null) {
8929            usesLibraryFiles.addAll(p.getAllCodePaths());
8930        }
8931    }
8932
8933    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8934            PackageParser.Package changingLib) throws PackageManagerException {
8935        if (pkg == null) {
8936            return;
8937        }
8938        ArraySet<String> usesLibraryFiles = null;
8939        if (pkg.usesLibraries != null) {
8940            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8941                    null, null, pkg.packageName, changingLib, true, null);
8942        }
8943        if (pkg.usesStaticLibraries != null) {
8944            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8945                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8946                    pkg.packageName, changingLib, true, usesLibraryFiles);
8947        }
8948        if (pkg.usesOptionalLibraries != null) {
8949            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8950                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8951        }
8952        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8953            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8954        } else {
8955            pkg.usesLibraryFiles = null;
8956        }
8957    }
8958
8959    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8960            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8961            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8962            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8963            throws PackageManagerException {
8964        final int libCount = requestedLibraries.size();
8965        for (int i = 0; i < libCount; i++) {
8966            final String libName = requestedLibraries.get(i);
8967            final int libVersion = requiredVersions != null ? requiredVersions[i]
8968                    : SharedLibraryInfo.VERSION_UNDEFINED;
8969            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8970            if (libEntry == null) {
8971                if (required) {
8972                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8973                            "Package " + packageName + " requires unavailable shared library "
8974                                    + libName + "; failing!");
8975                } else {
8976                    Slog.w(TAG, "Package " + packageName
8977                            + " desires unavailable shared library "
8978                            + libName + "; ignoring!");
8979                }
8980            } else {
8981                if (requiredVersions != null && requiredCertDigests != null) {
8982                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8983                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8984                            "Package " + packageName + " requires unavailable static shared"
8985                                    + " library " + libName + " version "
8986                                    + libEntry.info.getVersion() + "; failing!");
8987                    }
8988
8989                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8990                    if (libPkg == null) {
8991                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8992                                "Package " + packageName + " requires unavailable static shared"
8993                                        + " library; failing!");
8994                    }
8995
8996                    String expectedCertDigest = requiredCertDigests[i];
8997                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8998                                libPkg.mSignatures[0]);
8999                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9000                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9001                                "Package " + packageName + " requires differently signed" +
9002                                        " static shared library; failing!");
9003                    }
9004                }
9005
9006                if (outUsedLibraries == null) {
9007                    outUsedLibraries = new ArraySet<>();
9008                }
9009                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9010            }
9011        }
9012        return outUsedLibraries;
9013    }
9014
9015    private static boolean hasString(List<String> list, List<String> which) {
9016        if (list == null) {
9017            return false;
9018        }
9019        for (int i=list.size()-1; i>=0; i--) {
9020            for (int j=which.size()-1; j>=0; j--) {
9021                if (which.get(j).equals(list.get(i))) {
9022                    return true;
9023                }
9024            }
9025        }
9026        return false;
9027    }
9028
9029    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9030            PackageParser.Package changingPkg) {
9031        ArrayList<PackageParser.Package> res = null;
9032        for (PackageParser.Package pkg : mPackages.values()) {
9033            if (changingPkg != null
9034                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9035                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9036                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9037                            changingPkg.staticSharedLibName)) {
9038                return null;
9039            }
9040            if (res == null) {
9041                res = new ArrayList<>();
9042            }
9043            res.add(pkg);
9044            try {
9045                updateSharedLibrariesLPr(pkg, changingPkg);
9046            } catch (PackageManagerException e) {
9047                // If a system app update or an app and a required lib missing we
9048                // delete the package and for updated system apps keep the data as
9049                // it is better for the user to reinstall than to be in an limbo
9050                // state. Also libs disappearing under an app should never happen
9051                // - just in case.
9052                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9053                    final int flags = pkg.isUpdatedSystemApp()
9054                            ? PackageManager.DELETE_KEEP_DATA : 0;
9055                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9056                            flags , null, true, null);
9057                }
9058                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9059            }
9060        }
9061        return res;
9062    }
9063
9064    /**
9065     * Derive the value of the {@code cpuAbiOverride} based on the provided
9066     * value and an optional stored value from the package settings.
9067     */
9068    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9069        String cpuAbiOverride = null;
9070
9071        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9072            cpuAbiOverride = null;
9073        } else if (abiOverride != null) {
9074            cpuAbiOverride = abiOverride;
9075        } else if (settings != null) {
9076            cpuAbiOverride = settings.cpuAbiOverrideString;
9077        }
9078
9079        return cpuAbiOverride;
9080    }
9081
9082    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9083            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9084                    throws PackageManagerException {
9085        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9086        // If the package has children and this is the first dive in the function
9087        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9088        // whether all packages (parent and children) would be successfully scanned
9089        // before the actual scan since scanning mutates internal state and we want
9090        // to atomically install the package and its children.
9091        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9092            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9093                scanFlags |= SCAN_CHECK_ONLY;
9094            }
9095        } else {
9096            scanFlags &= ~SCAN_CHECK_ONLY;
9097        }
9098
9099        final PackageParser.Package scannedPkg;
9100        try {
9101            // Scan the parent
9102            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9103            // Scan the children
9104            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9105            for (int i = 0; i < childCount; i++) {
9106                PackageParser.Package childPkg = pkg.childPackages.get(i);
9107                scanPackageLI(childPkg, policyFlags,
9108                        scanFlags, currentTime, user);
9109            }
9110        } finally {
9111            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9112        }
9113
9114        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9115            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9116        }
9117
9118        return scannedPkg;
9119    }
9120
9121    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9122            int scanFlags, long currentTime, @Nullable UserHandle user)
9123                    throws PackageManagerException {
9124        boolean success = false;
9125        try {
9126            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9127                    currentTime, user);
9128            success = true;
9129            return res;
9130        } finally {
9131            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9132                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9133                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9134                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9135                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9136            }
9137        }
9138    }
9139
9140    /**
9141     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9142     */
9143    private static boolean apkHasCode(String fileName) {
9144        StrictJarFile jarFile = null;
9145        try {
9146            jarFile = new StrictJarFile(fileName,
9147                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9148            return jarFile.findEntry("classes.dex") != null;
9149        } catch (IOException ignore) {
9150        } finally {
9151            try {
9152                if (jarFile != null) {
9153                    jarFile.close();
9154                }
9155            } catch (IOException ignore) {}
9156        }
9157        return false;
9158    }
9159
9160    /**
9161     * Enforces code policy for the package. This ensures that if an APK has
9162     * declared hasCode="true" in its manifest that the APK actually contains
9163     * code.
9164     *
9165     * @throws PackageManagerException If bytecode could not be found when it should exist
9166     */
9167    private static void assertCodePolicy(PackageParser.Package pkg)
9168            throws PackageManagerException {
9169        final boolean shouldHaveCode =
9170                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9171        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9172            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9173                    "Package " + pkg.baseCodePath + " code is missing");
9174        }
9175
9176        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9177            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9178                final boolean splitShouldHaveCode =
9179                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9180                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9181                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9182                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9183                }
9184            }
9185        }
9186    }
9187
9188    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9189            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9190                    throws PackageManagerException {
9191        if (DEBUG_PACKAGE_SCANNING) {
9192            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9193                Log.d(TAG, "Scanning package " + pkg.packageName);
9194        }
9195
9196        applyPolicy(pkg, policyFlags);
9197
9198        assertPackageIsValid(pkg, policyFlags, scanFlags);
9199
9200        // Initialize package source and resource directories
9201        final File scanFile = new File(pkg.codePath);
9202        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9203        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9204
9205        SharedUserSetting suid = null;
9206        PackageSetting pkgSetting = null;
9207
9208        // Getting the package setting may have a side-effect, so if we
9209        // are only checking if scan would succeed, stash a copy of the
9210        // old setting to restore at the end.
9211        PackageSetting nonMutatedPs = null;
9212
9213        // We keep references to the derived CPU Abis from settings in oder to reuse
9214        // them in the case where we're not upgrading or booting for the first time.
9215        String primaryCpuAbiFromSettings = null;
9216        String secondaryCpuAbiFromSettings = null;
9217
9218        // writer
9219        synchronized (mPackages) {
9220            if (pkg.mSharedUserId != null) {
9221                // SIDE EFFECTS; may potentially allocate a new shared user
9222                suid = mSettings.getSharedUserLPw(
9223                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9224                if (DEBUG_PACKAGE_SCANNING) {
9225                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9226                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9227                                + "): packages=" + suid.packages);
9228                }
9229            }
9230
9231            // Check if we are renaming from an original package name.
9232            PackageSetting origPackage = null;
9233            String realName = null;
9234            if (pkg.mOriginalPackages != null) {
9235                // This package may need to be renamed to a previously
9236                // installed name.  Let's check on that...
9237                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9238                if (pkg.mOriginalPackages.contains(renamed)) {
9239                    // This package had originally been installed as the
9240                    // original name, and we have already taken care of
9241                    // transitioning to the new one.  Just update the new
9242                    // one to continue using the old name.
9243                    realName = pkg.mRealPackage;
9244                    if (!pkg.packageName.equals(renamed)) {
9245                        // Callers into this function may have already taken
9246                        // care of renaming the package; only do it here if
9247                        // it is not already done.
9248                        pkg.setPackageName(renamed);
9249                    }
9250                } else {
9251                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9252                        if ((origPackage = mSettings.getPackageLPr(
9253                                pkg.mOriginalPackages.get(i))) != null) {
9254                            // We do have the package already installed under its
9255                            // original name...  should we use it?
9256                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9257                                // New package is not compatible with original.
9258                                origPackage = null;
9259                                continue;
9260                            } else if (origPackage.sharedUser != null) {
9261                                // Make sure uid is compatible between packages.
9262                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9263                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9264                                            + " to " + pkg.packageName + ": old uid "
9265                                            + origPackage.sharedUser.name
9266                                            + " differs from " + pkg.mSharedUserId);
9267                                    origPackage = null;
9268                                    continue;
9269                                }
9270                                // TODO: Add case when shared user id is added [b/28144775]
9271                            } else {
9272                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9273                                        + pkg.packageName + " to old name " + origPackage.name);
9274                            }
9275                            break;
9276                        }
9277                    }
9278                }
9279            }
9280
9281            if (mTransferedPackages.contains(pkg.packageName)) {
9282                Slog.w(TAG, "Package " + pkg.packageName
9283                        + " was transferred to another, but its .apk remains");
9284            }
9285
9286            // See comments in nonMutatedPs declaration
9287            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9288                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9289                if (foundPs != null) {
9290                    nonMutatedPs = new PackageSetting(foundPs);
9291                }
9292            }
9293
9294            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9295                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9296                if (foundPs != null) {
9297                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9298                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9299                }
9300            }
9301
9302            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9303            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9304                PackageManagerService.reportSettingsProblem(Log.WARN,
9305                        "Package " + pkg.packageName + " shared user changed from "
9306                                + (pkgSetting.sharedUser != null
9307                                        ? pkgSetting.sharedUser.name : "<nothing>")
9308                                + " to "
9309                                + (suid != null ? suid.name : "<nothing>")
9310                                + "; replacing with new");
9311                pkgSetting = null;
9312            }
9313            final PackageSetting oldPkgSetting =
9314                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9315            final PackageSetting disabledPkgSetting =
9316                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9317
9318            String[] usesStaticLibraries = null;
9319            if (pkg.usesStaticLibraries != null) {
9320                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9321                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9322            }
9323
9324            if (pkgSetting == null) {
9325                final String parentPackageName = (pkg.parentPackage != null)
9326                        ? pkg.parentPackage.packageName : null;
9327                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9328                // REMOVE SharedUserSetting from method; update in a separate call
9329                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9330                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9331                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9332                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9333                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9334                        true /*allowInstall*/, instantApp, parentPackageName,
9335                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9336                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9337                // SIDE EFFECTS; updates system state; move elsewhere
9338                if (origPackage != null) {
9339                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9340                }
9341                mSettings.addUserToSettingLPw(pkgSetting);
9342            } else {
9343                // REMOVE SharedUserSetting from method; update in a separate call.
9344                //
9345                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9346                // secondaryCpuAbi are not known at this point so we always update them
9347                // to null here, only to reset them at a later point.
9348                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9349                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9350                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9351                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9352                        UserManagerService.getInstance(), usesStaticLibraries,
9353                        pkg.usesStaticLibrariesVersions);
9354            }
9355            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9356            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9357
9358            // SIDE EFFECTS; modifies system state; move elsewhere
9359            if (pkgSetting.origPackage != null) {
9360                // If we are first transitioning from an original package,
9361                // fix up the new package's name now.  We need to do this after
9362                // looking up the package under its new name, so getPackageLP
9363                // can take care of fiddling things correctly.
9364                pkg.setPackageName(origPackage.name);
9365
9366                // File a report about this.
9367                String msg = "New package " + pkgSetting.realName
9368                        + " renamed to replace old package " + pkgSetting.name;
9369                reportSettingsProblem(Log.WARN, msg);
9370
9371                // Make a note of it.
9372                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9373                    mTransferedPackages.add(origPackage.name);
9374                }
9375
9376                // No longer need to retain this.
9377                pkgSetting.origPackage = null;
9378            }
9379
9380            // SIDE EFFECTS; modifies system state; move elsewhere
9381            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9382                // Make a note of it.
9383                mTransferedPackages.add(pkg.packageName);
9384            }
9385
9386            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9387                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9388            }
9389
9390            if ((scanFlags & SCAN_BOOTING) == 0
9391                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9392                // Check all shared libraries and map to their actual file path.
9393                // We only do this here for apps not on a system dir, because those
9394                // are the only ones that can fail an install due to this.  We
9395                // will take care of the system apps by updating all of their
9396                // library paths after the scan is done. Also during the initial
9397                // scan don't update any libs as we do this wholesale after all
9398                // apps are scanned to avoid dependency based scanning.
9399                updateSharedLibrariesLPr(pkg, null);
9400            }
9401
9402            if (mFoundPolicyFile) {
9403                SELinuxMMAC.assignSeInfoValue(pkg);
9404            }
9405            pkg.applicationInfo.uid = pkgSetting.appId;
9406            pkg.mExtras = pkgSetting;
9407
9408
9409            // Static shared libs have same package with different versions where
9410            // we internally use a synthetic package name to allow multiple versions
9411            // of the same package, therefore we need to compare signatures against
9412            // the package setting for the latest library version.
9413            PackageSetting signatureCheckPs = pkgSetting;
9414            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9415                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9416                if (libraryEntry != null) {
9417                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9418                }
9419            }
9420
9421            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9422                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9423                    // We just determined the app is signed correctly, so bring
9424                    // over the latest parsed certs.
9425                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9426                } else {
9427                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9428                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9429                                "Package " + pkg.packageName + " upgrade keys do not match the "
9430                                + "previously installed version");
9431                    } else {
9432                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9433                        String msg = "System package " + pkg.packageName
9434                                + " signature changed; retaining data.";
9435                        reportSettingsProblem(Log.WARN, msg);
9436                    }
9437                }
9438            } else {
9439                try {
9440                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9441                    verifySignaturesLP(signatureCheckPs, pkg);
9442                    // We just determined the app is signed correctly, so bring
9443                    // over the latest parsed certs.
9444                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9445                } catch (PackageManagerException e) {
9446                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9447                        throw e;
9448                    }
9449                    // The signature has changed, but this package is in the system
9450                    // image...  let's recover!
9451                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9452                    // However...  if this package is part of a shared user, but it
9453                    // doesn't match the signature of the shared user, let's fail.
9454                    // What this means is that you can't change the signatures
9455                    // associated with an overall shared user, which doesn't seem all
9456                    // that unreasonable.
9457                    if (signatureCheckPs.sharedUser != null) {
9458                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9459                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9460                            throw new PackageManagerException(
9461                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9462                                    "Signature mismatch for shared user: "
9463                                            + pkgSetting.sharedUser);
9464                        }
9465                    }
9466                    // File a report about this.
9467                    String msg = "System package " + pkg.packageName
9468                            + " signature changed; retaining data.";
9469                    reportSettingsProblem(Log.WARN, msg);
9470                }
9471            }
9472
9473            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9474                // This package wants to adopt ownership of permissions from
9475                // another package.
9476                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9477                    final String origName = pkg.mAdoptPermissions.get(i);
9478                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9479                    if (orig != null) {
9480                        if (verifyPackageUpdateLPr(orig, pkg)) {
9481                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9482                                    + pkg.packageName);
9483                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9484                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9485                        }
9486                    }
9487                }
9488            }
9489        }
9490
9491        pkg.applicationInfo.processName = fixProcessName(
9492                pkg.applicationInfo.packageName,
9493                pkg.applicationInfo.processName);
9494
9495        if (pkg != mPlatformPackage) {
9496            // Get all of our default paths setup
9497            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9498        }
9499
9500        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9501
9502        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9503            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9504                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9505                derivePackageAbi(
9506                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9507                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9508
9509                // Some system apps still use directory structure for native libraries
9510                // in which case we might end up not detecting abi solely based on apk
9511                // structure. Try to detect abi based on directory structure.
9512                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9513                        pkg.applicationInfo.primaryCpuAbi == null) {
9514                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9515                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9516                }
9517            } else {
9518                // This is not a first boot or an upgrade, don't bother deriving the
9519                // ABI during the scan. Instead, trust the value that was stored in the
9520                // package setting.
9521                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9522                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9523
9524                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9525
9526                if (DEBUG_ABI_SELECTION) {
9527                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9528                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9529                        pkg.applicationInfo.secondaryCpuAbi);
9530                }
9531            }
9532        } else {
9533            if ((scanFlags & SCAN_MOVE) != 0) {
9534                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9535                // but we already have this packages package info in the PackageSetting. We just
9536                // use that and derive the native library path based on the new codepath.
9537                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9538                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9539            }
9540
9541            // Set native library paths again. For moves, the path will be updated based on the
9542            // ABIs we've determined above. For non-moves, the path will be updated based on the
9543            // ABIs we determined during compilation, but the path will depend on the final
9544            // package path (after the rename away from the stage path).
9545            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9546        }
9547
9548        // This is a special case for the "system" package, where the ABI is
9549        // dictated by the zygote configuration (and init.rc). We should keep track
9550        // of this ABI so that we can deal with "normal" applications that run under
9551        // the same UID correctly.
9552        if (mPlatformPackage == pkg) {
9553            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9554                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9555        }
9556
9557        // If there's a mismatch between the abi-override in the package setting
9558        // and the abiOverride specified for the install. Warn about this because we
9559        // would've already compiled the app without taking the package setting into
9560        // account.
9561        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9562            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9563                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9564                        " for package " + pkg.packageName);
9565            }
9566        }
9567
9568        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9569        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9570        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9571
9572        // Copy the derived override back to the parsed package, so that we can
9573        // update the package settings accordingly.
9574        pkg.cpuAbiOverride = cpuAbiOverride;
9575
9576        if (DEBUG_ABI_SELECTION) {
9577            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9578                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9579                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9580        }
9581
9582        // Push the derived path down into PackageSettings so we know what to
9583        // clean up at uninstall time.
9584        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9585
9586        if (DEBUG_ABI_SELECTION) {
9587            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9588                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9589                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9590        }
9591
9592        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9593        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9594            // We don't do this here during boot because we can do it all
9595            // at once after scanning all existing packages.
9596            //
9597            // We also do this *before* we perform dexopt on this package, so that
9598            // we can avoid redundant dexopts, and also to make sure we've got the
9599            // code and package path correct.
9600            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9601        }
9602
9603        if (mFactoryTest && pkg.requestedPermissions.contains(
9604                android.Manifest.permission.FACTORY_TEST)) {
9605            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9606        }
9607
9608        if (isSystemApp(pkg)) {
9609            pkgSetting.isOrphaned = true;
9610        }
9611
9612        // Take care of first install / last update times.
9613        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9614        if (currentTime != 0) {
9615            if (pkgSetting.firstInstallTime == 0) {
9616                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9617            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9618                pkgSetting.lastUpdateTime = currentTime;
9619            }
9620        } else if (pkgSetting.firstInstallTime == 0) {
9621            // We need *something*.  Take time time stamp of the file.
9622            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9623        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9624            if (scanFileTime != pkgSetting.timeStamp) {
9625                // A package on the system image has changed; consider this
9626                // to be an update.
9627                pkgSetting.lastUpdateTime = scanFileTime;
9628            }
9629        }
9630        pkgSetting.setTimeStamp(scanFileTime);
9631
9632        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9633            if (nonMutatedPs != null) {
9634                synchronized (mPackages) {
9635                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9636                }
9637            }
9638        } else {
9639            final int userId = user == null ? 0 : user.getIdentifier();
9640            // Modify state for the given package setting
9641            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9642                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9643            if (pkgSetting.getInstantApp(userId)) {
9644                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9645            }
9646        }
9647        return pkg;
9648    }
9649
9650    /**
9651     * Applies policy to the parsed package based upon the given policy flags.
9652     * Ensures the package is in a good state.
9653     * <p>
9654     * Implementation detail: This method must NOT have any side effect. It would
9655     * ideally be static, but, it requires locks to read system state.
9656     */
9657    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9658        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9659            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9660            if (pkg.applicationInfo.isDirectBootAware()) {
9661                // we're direct boot aware; set for all components
9662                for (PackageParser.Service s : pkg.services) {
9663                    s.info.encryptionAware = s.info.directBootAware = true;
9664                }
9665                for (PackageParser.Provider p : pkg.providers) {
9666                    p.info.encryptionAware = p.info.directBootAware = true;
9667                }
9668                for (PackageParser.Activity a : pkg.activities) {
9669                    a.info.encryptionAware = a.info.directBootAware = true;
9670                }
9671                for (PackageParser.Activity r : pkg.receivers) {
9672                    r.info.encryptionAware = r.info.directBootAware = true;
9673                }
9674            }
9675        } else {
9676            // Only allow system apps to be flagged as core apps.
9677            pkg.coreApp = false;
9678            // clear flags not applicable to regular apps
9679            pkg.applicationInfo.privateFlags &=
9680                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9681            pkg.applicationInfo.privateFlags &=
9682                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9683        }
9684        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9685
9686        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9687            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9688        }
9689
9690        if (!isSystemApp(pkg)) {
9691            // Only system apps can use these features.
9692            pkg.mOriginalPackages = null;
9693            pkg.mRealPackage = null;
9694            pkg.mAdoptPermissions = null;
9695        }
9696    }
9697
9698    /**
9699     * Asserts the parsed package is valid according to the given policy. If the
9700     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9701     * <p>
9702     * Implementation detail: This method must NOT have any side effects. It would
9703     * ideally be static, but, it requires locks to read system state.
9704     *
9705     * @throws PackageManagerException If the package fails any of the validation checks
9706     */
9707    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9708            throws PackageManagerException {
9709        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9710            assertCodePolicy(pkg);
9711        }
9712
9713        if (pkg.applicationInfo.getCodePath() == null ||
9714                pkg.applicationInfo.getResourcePath() == null) {
9715            // Bail out. The resource and code paths haven't been set.
9716            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9717                    "Code and resource paths haven't been set correctly");
9718        }
9719
9720        // Make sure we're not adding any bogus keyset info
9721        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9722        ksms.assertScannedPackageValid(pkg);
9723
9724        synchronized (mPackages) {
9725            // The special "android" package can only be defined once
9726            if (pkg.packageName.equals("android")) {
9727                if (mAndroidApplication != null) {
9728                    Slog.w(TAG, "*************************************************");
9729                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9730                    Slog.w(TAG, " codePath=" + pkg.codePath);
9731                    Slog.w(TAG, "*************************************************");
9732                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9733                            "Core android package being redefined.  Skipping.");
9734                }
9735            }
9736
9737            // A package name must be unique; don't allow duplicates
9738            if (mPackages.containsKey(pkg.packageName)) {
9739                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9740                        "Application package " + pkg.packageName
9741                        + " already installed.  Skipping duplicate.");
9742            }
9743
9744            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9745                // Static libs have a synthetic package name containing the version
9746                // but we still want the base name to be unique.
9747                if (mPackages.containsKey(pkg.manifestPackageName)) {
9748                    throw new PackageManagerException(
9749                            "Duplicate static shared lib provider package");
9750                }
9751
9752                // Static shared libraries should have at least O target SDK
9753                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9754                    throw new PackageManagerException(
9755                            "Packages declaring static-shared libs must target O SDK or higher");
9756                }
9757
9758                // Package declaring static a shared lib cannot be instant apps
9759                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9760                    throw new PackageManagerException(
9761                            "Packages declaring static-shared libs cannot be instant apps");
9762                }
9763
9764                // Package declaring static a shared lib cannot be renamed since the package
9765                // name is synthetic and apps can't code around package manager internals.
9766                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9767                    throw new PackageManagerException(
9768                            "Packages declaring static-shared libs cannot be renamed");
9769                }
9770
9771                // Package declaring static a shared lib cannot declare child packages
9772                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9773                    throw new PackageManagerException(
9774                            "Packages declaring static-shared libs cannot have child packages");
9775                }
9776
9777                // Package declaring static a shared lib cannot declare dynamic libs
9778                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9779                    throw new PackageManagerException(
9780                            "Packages declaring static-shared libs cannot declare dynamic libs");
9781                }
9782
9783                // Package declaring static a shared lib cannot declare shared users
9784                if (pkg.mSharedUserId != null) {
9785                    throw new PackageManagerException(
9786                            "Packages declaring static-shared libs cannot declare shared users");
9787                }
9788
9789                // Static shared libs cannot declare activities
9790                if (!pkg.activities.isEmpty()) {
9791                    throw new PackageManagerException(
9792                            "Static shared libs cannot declare activities");
9793                }
9794
9795                // Static shared libs cannot declare services
9796                if (!pkg.services.isEmpty()) {
9797                    throw new PackageManagerException(
9798                            "Static shared libs cannot declare services");
9799                }
9800
9801                // Static shared libs cannot declare providers
9802                if (!pkg.providers.isEmpty()) {
9803                    throw new PackageManagerException(
9804                            "Static shared libs cannot declare content providers");
9805                }
9806
9807                // Static shared libs cannot declare receivers
9808                if (!pkg.receivers.isEmpty()) {
9809                    throw new PackageManagerException(
9810                            "Static shared libs cannot declare broadcast receivers");
9811                }
9812
9813                // Static shared libs cannot declare permission groups
9814                if (!pkg.permissionGroups.isEmpty()) {
9815                    throw new PackageManagerException(
9816                            "Static shared libs cannot declare permission groups");
9817                }
9818
9819                // Static shared libs cannot declare permissions
9820                if (!pkg.permissions.isEmpty()) {
9821                    throw new PackageManagerException(
9822                            "Static shared libs cannot declare permissions");
9823                }
9824
9825                // Static shared libs cannot declare protected broadcasts
9826                if (pkg.protectedBroadcasts != null) {
9827                    throw new PackageManagerException(
9828                            "Static shared libs cannot declare protected broadcasts");
9829                }
9830
9831                // Static shared libs cannot be overlay targets
9832                if (pkg.mOverlayTarget != null) {
9833                    throw new PackageManagerException(
9834                            "Static shared libs cannot be overlay targets");
9835                }
9836
9837                // The version codes must be ordered as lib versions
9838                int minVersionCode = Integer.MIN_VALUE;
9839                int maxVersionCode = Integer.MAX_VALUE;
9840
9841                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9842                        pkg.staticSharedLibName);
9843                if (versionedLib != null) {
9844                    final int versionCount = versionedLib.size();
9845                    for (int i = 0; i < versionCount; i++) {
9846                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9847                        // TODO: We will change version code to long, so in the new API it is long
9848                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9849                                .getVersionCode();
9850                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9851                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9852                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9853                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9854                        } else {
9855                            minVersionCode = maxVersionCode = libVersionCode;
9856                            break;
9857                        }
9858                    }
9859                }
9860                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9861                    throw new PackageManagerException("Static shared"
9862                            + " lib version codes must be ordered as lib versions");
9863                }
9864            }
9865
9866            // Only privileged apps and updated privileged apps can add child packages.
9867            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9868                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9869                    throw new PackageManagerException("Only privileged apps can add child "
9870                            + "packages. Ignoring package " + pkg.packageName);
9871                }
9872                final int childCount = pkg.childPackages.size();
9873                for (int i = 0; i < childCount; i++) {
9874                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9875                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9876                            childPkg.packageName)) {
9877                        throw new PackageManagerException("Can't override child of "
9878                                + "another disabled app. Ignoring package " + pkg.packageName);
9879                    }
9880                }
9881            }
9882
9883            // If we're only installing presumed-existing packages, require that the
9884            // scanned APK is both already known and at the path previously established
9885            // for it.  Previously unknown packages we pick up normally, but if we have an
9886            // a priori expectation about this package's install presence, enforce it.
9887            // With a singular exception for new system packages. When an OTA contains
9888            // a new system package, we allow the codepath to change from a system location
9889            // to the user-installed location. If we don't allow this change, any newer,
9890            // user-installed version of the application will be ignored.
9891            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9892                if (mExpectingBetter.containsKey(pkg.packageName)) {
9893                    logCriticalInfo(Log.WARN,
9894                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9895                } else {
9896                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9897                    if (known != null) {
9898                        if (DEBUG_PACKAGE_SCANNING) {
9899                            Log.d(TAG, "Examining " + pkg.codePath
9900                                    + " and requiring known paths " + known.codePathString
9901                                    + " & " + known.resourcePathString);
9902                        }
9903                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9904                                || !pkg.applicationInfo.getResourcePath().equals(
9905                                        known.resourcePathString)) {
9906                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9907                                    "Application package " + pkg.packageName
9908                                    + " found at " + pkg.applicationInfo.getCodePath()
9909                                    + " but expected at " + known.codePathString
9910                                    + "; ignoring.");
9911                        }
9912                    }
9913                }
9914            }
9915
9916            // Verify that this new package doesn't have any content providers
9917            // that conflict with existing packages.  Only do this if the
9918            // package isn't already installed, since we don't want to break
9919            // things that are installed.
9920            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9921                final int N = pkg.providers.size();
9922                int i;
9923                for (i=0; i<N; i++) {
9924                    PackageParser.Provider p = pkg.providers.get(i);
9925                    if (p.info.authority != null) {
9926                        String names[] = p.info.authority.split(";");
9927                        for (int j = 0; j < names.length; j++) {
9928                            if (mProvidersByAuthority.containsKey(names[j])) {
9929                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9930                                final String otherPackageName =
9931                                        ((other != null && other.getComponentName() != null) ?
9932                                                other.getComponentName().getPackageName() : "?");
9933                                throw new PackageManagerException(
9934                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9935                                        "Can't install because provider name " + names[j]
9936                                                + " (in package " + pkg.applicationInfo.packageName
9937                                                + ") is already used by " + otherPackageName);
9938                            }
9939                        }
9940                    }
9941                }
9942            }
9943        }
9944    }
9945
9946    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9947            int type, String declaringPackageName, int declaringVersionCode) {
9948        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9949        if (versionedLib == null) {
9950            versionedLib = new SparseArray<>();
9951            mSharedLibraries.put(name, versionedLib);
9952            if (type == SharedLibraryInfo.TYPE_STATIC) {
9953                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9954            }
9955        } else if (versionedLib.indexOfKey(version) >= 0) {
9956            return false;
9957        }
9958        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9959                version, type, declaringPackageName, declaringVersionCode);
9960        versionedLib.put(version, libEntry);
9961        return true;
9962    }
9963
9964    private boolean removeSharedLibraryLPw(String name, int version) {
9965        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9966        if (versionedLib == null) {
9967            return false;
9968        }
9969        final int libIdx = versionedLib.indexOfKey(version);
9970        if (libIdx < 0) {
9971            return false;
9972        }
9973        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9974        versionedLib.remove(version);
9975        if (versionedLib.size() <= 0) {
9976            mSharedLibraries.remove(name);
9977            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9978                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9979                        .getPackageName());
9980            }
9981        }
9982        return true;
9983    }
9984
9985    /**
9986     * Adds a scanned package to the system. When this method is finished, the package will
9987     * be available for query, resolution, etc...
9988     */
9989    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9990            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9991        final String pkgName = pkg.packageName;
9992        if (mCustomResolverComponentName != null &&
9993                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9994            setUpCustomResolverActivity(pkg);
9995        }
9996
9997        if (pkg.packageName.equals("android")) {
9998            synchronized (mPackages) {
9999                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10000                    // Set up information for our fall-back user intent resolution activity.
10001                    mPlatformPackage = pkg;
10002                    pkg.mVersionCode = mSdkVersion;
10003                    mAndroidApplication = pkg.applicationInfo;
10004                    if (!mResolverReplaced) {
10005                        mResolveActivity.applicationInfo = mAndroidApplication;
10006                        mResolveActivity.name = ResolverActivity.class.getName();
10007                        mResolveActivity.packageName = mAndroidApplication.packageName;
10008                        mResolveActivity.processName = "system:ui";
10009                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10010                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10011                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10012                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10013                        mResolveActivity.exported = true;
10014                        mResolveActivity.enabled = true;
10015                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10016                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10017                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10018                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10019                                | ActivityInfo.CONFIG_ORIENTATION
10020                                | ActivityInfo.CONFIG_KEYBOARD
10021                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10022                        mResolveInfo.activityInfo = mResolveActivity;
10023                        mResolveInfo.priority = 0;
10024                        mResolveInfo.preferredOrder = 0;
10025                        mResolveInfo.match = 0;
10026                        mResolveComponentName = new ComponentName(
10027                                mAndroidApplication.packageName, mResolveActivity.name);
10028                    }
10029                }
10030            }
10031        }
10032
10033        ArrayList<PackageParser.Package> clientLibPkgs = null;
10034        // writer
10035        synchronized (mPackages) {
10036            boolean hasStaticSharedLibs = false;
10037
10038            // Any app can add new static shared libraries
10039            if (pkg.staticSharedLibName != null) {
10040                // Static shared libs don't allow renaming as they have synthetic package
10041                // names to allow install of multiple versions, so use name from manifest.
10042                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10043                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10044                        pkg.manifestPackageName, pkg.mVersionCode)) {
10045                    hasStaticSharedLibs = true;
10046                } else {
10047                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10048                                + pkg.staticSharedLibName + " already exists; skipping");
10049                }
10050                // Static shared libs cannot be updated once installed since they
10051                // use synthetic package name which includes the version code, so
10052                // not need to update other packages's shared lib dependencies.
10053            }
10054
10055            if (!hasStaticSharedLibs
10056                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10057                // Only system apps can add new dynamic shared libraries.
10058                if (pkg.libraryNames != null) {
10059                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10060                        String name = pkg.libraryNames.get(i);
10061                        boolean allowed = false;
10062                        if (pkg.isUpdatedSystemApp()) {
10063                            // New library entries can only be added through the
10064                            // system image.  This is important to get rid of a lot
10065                            // of nasty edge cases: for example if we allowed a non-
10066                            // system update of the app to add a library, then uninstalling
10067                            // the update would make the library go away, and assumptions
10068                            // we made such as through app install filtering would now
10069                            // have allowed apps on the device which aren't compatible
10070                            // with it.  Better to just have the restriction here, be
10071                            // conservative, and create many fewer cases that can negatively
10072                            // impact the user experience.
10073                            final PackageSetting sysPs = mSettings
10074                                    .getDisabledSystemPkgLPr(pkg.packageName);
10075                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10076                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10077                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10078                                        allowed = true;
10079                                        break;
10080                                    }
10081                                }
10082                            }
10083                        } else {
10084                            allowed = true;
10085                        }
10086                        if (allowed) {
10087                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10088                                    SharedLibraryInfo.VERSION_UNDEFINED,
10089                                    SharedLibraryInfo.TYPE_DYNAMIC,
10090                                    pkg.packageName, pkg.mVersionCode)) {
10091                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10092                                        + name + " already exists; skipping");
10093                            }
10094                        } else {
10095                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10096                                    + name + " that is not declared on system image; skipping");
10097                        }
10098                    }
10099
10100                    if ((scanFlags & SCAN_BOOTING) == 0) {
10101                        // If we are not booting, we need to update any applications
10102                        // that are clients of our shared library.  If we are booting,
10103                        // this will all be done once the scan is complete.
10104                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10105                    }
10106                }
10107            }
10108        }
10109
10110        if ((scanFlags & SCAN_BOOTING) != 0) {
10111            // No apps can run during boot scan, so they don't need to be frozen
10112        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10113            // Caller asked to not kill app, so it's probably not frozen
10114        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10115            // Caller asked us to ignore frozen check for some reason; they
10116            // probably didn't know the package name
10117        } else {
10118            // We're doing major surgery on this package, so it better be frozen
10119            // right now to keep it from launching
10120            checkPackageFrozen(pkgName);
10121        }
10122
10123        // Also need to kill any apps that are dependent on the library.
10124        if (clientLibPkgs != null) {
10125            for (int i=0; i<clientLibPkgs.size(); i++) {
10126                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10127                killApplication(clientPkg.applicationInfo.packageName,
10128                        clientPkg.applicationInfo.uid, "update lib");
10129            }
10130        }
10131
10132        // writer
10133        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10134
10135        synchronized (mPackages) {
10136            // We don't expect installation to fail beyond this point
10137
10138            // Add the new setting to mSettings
10139            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10140            // Add the new setting to mPackages
10141            mPackages.put(pkg.applicationInfo.packageName, pkg);
10142            // Make sure we don't accidentally delete its data.
10143            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10144            while (iter.hasNext()) {
10145                PackageCleanItem item = iter.next();
10146                if (pkgName.equals(item.packageName)) {
10147                    iter.remove();
10148                }
10149            }
10150
10151            // Add the package's KeySets to the global KeySetManagerService
10152            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10153            ksms.addScannedPackageLPw(pkg);
10154
10155            int N = pkg.providers.size();
10156            StringBuilder r = null;
10157            int i;
10158            for (i=0; i<N; i++) {
10159                PackageParser.Provider p = pkg.providers.get(i);
10160                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10161                        p.info.processName);
10162                mProviders.addProvider(p);
10163                p.syncable = p.info.isSyncable;
10164                if (p.info.authority != null) {
10165                    String names[] = p.info.authority.split(";");
10166                    p.info.authority = null;
10167                    for (int j = 0; j < names.length; j++) {
10168                        if (j == 1 && p.syncable) {
10169                            // We only want the first authority for a provider to possibly be
10170                            // syncable, so if we already added this provider using a different
10171                            // authority clear the syncable flag. We copy the provider before
10172                            // changing it because the mProviders object contains a reference
10173                            // to a provider that we don't want to change.
10174                            // Only do this for the second authority since the resulting provider
10175                            // object can be the same for all future authorities for this provider.
10176                            p = new PackageParser.Provider(p);
10177                            p.syncable = false;
10178                        }
10179                        if (!mProvidersByAuthority.containsKey(names[j])) {
10180                            mProvidersByAuthority.put(names[j], p);
10181                            if (p.info.authority == null) {
10182                                p.info.authority = names[j];
10183                            } else {
10184                                p.info.authority = p.info.authority + ";" + names[j];
10185                            }
10186                            if (DEBUG_PACKAGE_SCANNING) {
10187                                if (chatty)
10188                                    Log.d(TAG, "Registered content provider: " + names[j]
10189                                            + ", className = " + p.info.name + ", isSyncable = "
10190                                            + p.info.isSyncable);
10191                            }
10192                        } else {
10193                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10194                            Slog.w(TAG, "Skipping provider name " + names[j] +
10195                                    " (in package " + pkg.applicationInfo.packageName +
10196                                    "): name already used by "
10197                                    + ((other != null && other.getComponentName() != null)
10198                                            ? other.getComponentName().getPackageName() : "?"));
10199                        }
10200                    }
10201                }
10202                if (chatty) {
10203                    if (r == null) {
10204                        r = new StringBuilder(256);
10205                    } else {
10206                        r.append(' ');
10207                    }
10208                    r.append(p.info.name);
10209                }
10210            }
10211            if (r != null) {
10212                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10213            }
10214
10215            N = pkg.services.size();
10216            r = null;
10217            for (i=0; i<N; i++) {
10218                PackageParser.Service s = pkg.services.get(i);
10219                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10220                        s.info.processName);
10221                mServices.addService(s);
10222                if (chatty) {
10223                    if (r == null) {
10224                        r = new StringBuilder(256);
10225                    } else {
10226                        r.append(' ');
10227                    }
10228                    r.append(s.info.name);
10229                }
10230            }
10231            if (r != null) {
10232                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10233            }
10234
10235            N = pkg.receivers.size();
10236            r = null;
10237            for (i=0; i<N; i++) {
10238                PackageParser.Activity a = pkg.receivers.get(i);
10239                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10240                        a.info.processName);
10241                mReceivers.addActivity(a, "receiver");
10242                if (chatty) {
10243                    if (r == null) {
10244                        r = new StringBuilder(256);
10245                    } else {
10246                        r.append(' ');
10247                    }
10248                    r.append(a.info.name);
10249                }
10250            }
10251            if (r != null) {
10252                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10253            }
10254
10255            N = pkg.activities.size();
10256            r = null;
10257            for (i=0; i<N; i++) {
10258                PackageParser.Activity a = pkg.activities.get(i);
10259                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10260                        a.info.processName);
10261                mActivities.addActivity(a, "activity");
10262                if (chatty) {
10263                    if (r == null) {
10264                        r = new StringBuilder(256);
10265                    } else {
10266                        r.append(' ');
10267                    }
10268                    r.append(a.info.name);
10269                }
10270            }
10271            if (r != null) {
10272                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10273            }
10274
10275            N = pkg.permissionGroups.size();
10276            r = null;
10277            for (i=0; i<N; i++) {
10278                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10279                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10280                final String curPackageName = cur == null ? null : cur.info.packageName;
10281                // Dont allow ephemeral apps to define new permission groups.
10282                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10283                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10284                            + pg.info.packageName
10285                            + " ignored: instant apps cannot define new permission groups.");
10286                    continue;
10287                }
10288                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10289                if (cur == null || isPackageUpdate) {
10290                    mPermissionGroups.put(pg.info.name, pg);
10291                    if (chatty) {
10292                        if (r == null) {
10293                            r = new StringBuilder(256);
10294                        } else {
10295                            r.append(' ');
10296                        }
10297                        if (isPackageUpdate) {
10298                            r.append("UPD:");
10299                        }
10300                        r.append(pg.info.name);
10301                    }
10302                } else {
10303                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10304                            + pg.info.packageName + " ignored: original from "
10305                            + cur.info.packageName);
10306                    if (chatty) {
10307                        if (r == null) {
10308                            r = new StringBuilder(256);
10309                        } else {
10310                            r.append(' ');
10311                        }
10312                        r.append("DUP:");
10313                        r.append(pg.info.name);
10314                    }
10315                }
10316            }
10317            if (r != null) {
10318                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10319            }
10320
10321            N = pkg.permissions.size();
10322            r = null;
10323            for (i=0; i<N; i++) {
10324                PackageParser.Permission p = pkg.permissions.get(i);
10325
10326                // Dont allow ephemeral apps to define new permissions.
10327                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10328                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10329                            + p.info.packageName
10330                            + " ignored: instant apps cannot define new permissions.");
10331                    continue;
10332                }
10333
10334                // Assume by default that we did not install this permission into the system.
10335                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10336
10337                // Now that permission groups have a special meaning, we ignore permission
10338                // groups for legacy apps to prevent unexpected behavior. In particular,
10339                // permissions for one app being granted to someone just becase they happen
10340                // to be in a group defined by another app (before this had no implications).
10341                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10342                    p.group = mPermissionGroups.get(p.info.group);
10343                    // Warn for a permission in an unknown group.
10344                    if (p.info.group != null && p.group == null) {
10345                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10346                                + p.info.packageName + " in an unknown group " + p.info.group);
10347                    }
10348                }
10349
10350                ArrayMap<String, BasePermission> permissionMap =
10351                        p.tree ? mSettings.mPermissionTrees
10352                                : mSettings.mPermissions;
10353                BasePermission bp = permissionMap.get(p.info.name);
10354
10355                // Allow system apps to redefine non-system permissions
10356                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10357                    final boolean currentOwnerIsSystem = (bp.perm != null
10358                            && isSystemApp(bp.perm.owner));
10359                    if (isSystemApp(p.owner)) {
10360                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10361                            // It's a built-in permission and no owner, take ownership now
10362                            bp.packageSetting = pkgSetting;
10363                            bp.perm = p;
10364                            bp.uid = pkg.applicationInfo.uid;
10365                            bp.sourcePackage = p.info.packageName;
10366                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10367                        } else if (!currentOwnerIsSystem) {
10368                            String msg = "New decl " + p.owner + " of permission  "
10369                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10370                            reportSettingsProblem(Log.WARN, msg);
10371                            bp = null;
10372                        }
10373                    }
10374                }
10375
10376                if (bp == null) {
10377                    bp = new BasePermission(p.info.name, p.info.packageName,
10378                            BasePermission.TYPE_NORMAL);
10379                    permissionMap.put(p.info.name, bp);
10380                }
10381
10382                if (bp.perm == null) {
10383                    if (bp.sourcePackage == null
10384                            || bp.sourcePackage.equals(p.info.packageName)) {
10385                        BasePermission tree = findPermissionTreeLP(p.info.name);
10386                        if (tree == null
10387                                || tree.sourcePackage.equals(p.info.packageName)) {
10388                            bp.packageSetting = pkgSetting;
10389                            bp.perm = p;
10390                            bp.uid = pkg.applicationInfo.uid;
10391                            bp.sourcePackage = p.info.packageName;
10392                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10393                            if (chatty) {
10394                                if (r == null) {
10395                                    r = new StringBuilder(256);
10396                                } else {
10397                                    r.append(' ');
10398                                }
10399                                r.append(p.info.name);
10400                            }
10401                        } else {
10402                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10403                                    + p.info.packageName + " ignored: base tree "
10404                                    + tree.name + " is from package "
10405                                    + tree.sourcePackage);
10406                        }
10407                    } else {
10408                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10409                                + p.info.packageName + " ignored: original from "
10410                                + bp.sourcePackage);
10411                    }
10412                } else if (chatty) {
10413                    if (r == null) {
10414                        r = new StringBuilder(256);
10415                    } else {
10416                        r.append(' ');
10417                    }
10418                    r.append("DUP:");
10419                    r.append(p.info.name);
10420                }
10421                if (bp.perm == p) {
10422                    bp.protectionLevel = p.info.protectionLevel;
10423                }
10424            }
10425
10426            if (r != null) {
10427                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10428            }
10429
10430            N = pkg.instrumentation.size();
10431            r = null;
10432            for (i=0; i<N; i++) {
10433                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10434                a.info.packageName = pkg.applicationInfo.packageName;
10435                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10436                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10437                a.info.splitNames = pkg.splitNames;
10438                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10439                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10440                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10441                a.info.dataDir = pkg.applicationInfo.dataDir;
10442                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10443                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10444                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10445                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10446                mInstrumentation.put(a.getComponentName(), a);
10447                if (chatty) {
10448                    if (r == null) {
10449                        r = new StringBuilder(256);
10450                    } else {
10451                        r.append(' ');
10452                    }
10453                    r.append(a.info.name);
10454                }
10455            }
10456            if (r != null) {
10457                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10458            }
10459
10460            if (pkg.protectedBroadcasts != null) {
10461                N = pkg.protectedBroadcasts.size();
10462                for (i=0; i<N; i++) {
10463                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10464                }
10465            }
10466        }
10467
10468        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10469    }
10470
10471    /**
10472     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10473     * is derived purely on the basis of the contents of {@code scanFile} and
10474     * {@code cpuAbiOverride}.
10475     *
10476     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10477     */
10478    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10479                                 String cpuAbiOverride, boolean extractLibs,
10480                                 File appLib32InstallDir)
10481            throws PackageManagerException {
10482        // Give ourselves some initial paths; we'll come back for another
10483        // pass once we've determined ABI below.
10484        setNativeLibraryPaths(pkg, appLib32InstallDir);
10485
10486        // We would never need to extract libs for forward-locked and external packages,
10487        // since the container service will do it for us. We shouldn't attempt to
10488        // extract libs from system app when it was not updated.
10489        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10490                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10491            extractLibs = false;
10492        }
10493
10494        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10495        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10496
10497        NativeLibraryHelper.Handle handle = null;
10498        try {
10499            handle = NativeLibraryHelper.Handle.create(pkg);
10500            // TODO(multiArch): This can be null for apps that didn't go through the
10501            // usual installation process. We can calculate it again, like we
10502            // do during install time.
10503            //
10504            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10505            // unnecessary.
10506            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10507
10508            // Null out the abis so that they can be recalculated.
10509            pkg.applicationInfo.primaryCpuAbi = null;
10510            pkg.applicationInfo.secondaryCpuAbi = null;
10511            if (isMultiArch(pkg.applicationInfo)) {
10512                // Warn if we've set an abiOverride for multi-lib packages..
10513                // By definition, we need to copy both 32 and 64 bit libraries for
10514                // such packages.
10515                if (pkg.cpuAbiOverride != null
10516                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10517                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10518                }
10519
10520                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10521                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10522                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10523                    if (extractLibs) {
10524                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10525                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10526                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10527                                useIsaSpecificSubdirs);
10528                    } else {
10529                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10530                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10531                    }
10532                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10533                }
10534
10535                maybeThrowExceptionForMultiArchCopy(
10536                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10537
10538                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10539                    if (extractLibs) {
10540                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10541                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10542                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10543                                useIsaSpecificSubdirs);
10544                    } else {
10545                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10546                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10547                    }
10548                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10549                }
10550
10551                maybeThrowExceptionForMultiArchCopy(
10552                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10553
10554                if (abi64 >= 0) {
10555                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10556                }
10557
10558                if (abi32 >= 0) {
10559                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10560                    if (abi64 >= 0) {
10561                        if (pkg.use32bitAbi) {
10562                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10563                            pkg.applicationInfo.primaryCpuAbi = abi;
10564                        } else {
10565                            pkg.applicationInfo.secondaryCpuAbi = abi;
10566                        }
10567                    } else {
10568                        pkg.applicationInfo.primaryCpuAbi = abi;
10569                    }
10570                }
10571
10572            } else {
10573                String[] abiList = (cpuAbiOverride != null) ?
10574                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10575
10576                // Enable gross and lame hacks for apps that are built with old
10577                // SDK tools. We must scan their APKs for renderscript bitcode and
10578                // not launch them if it's present. Don't bother checking on devices
10579                // that don't have 64 bit support.
10580                boolean needsRenderScriptOverride = false;
10581                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10582                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10583                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10584                    needsRenderScriptOverride = true;
10585                }
10586
10587                final int copyRet;
10588                if (extractLibs) {
10589                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10590                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10591                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10592                } else {
10593                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10594                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10595                }
10596                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10597
10598                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10599                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10600                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10601                }
10602
10603                if (copyRet >= 0) {
10604                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10605                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10606                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10607                } else if (needsRenderScriptOverride) {
10608                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10609                }
10610            }
10611        } catch (IOException ioe) {
10612            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10613        } finally {
10614            IoUtils.closeQuietly(handle);
10615        }
10616
10617        // Now that we've calculated the ABIs and determined if it's an internal app,
10618        // we will go ahead and populate the nativeLibraryPath.
10619        setNativeLibraryPaths(pkg, appLib32InstallDir);
10620    }
10621
10622    /**
10623     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10624     * i.e, so that all packages can be run inside a single process if required.
10625     *
10626     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10627     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10628     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10629     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10630     * updating a package that belongs to a shared user.
10631     *
10632     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10633     * adds unnecessary complexity.
10634     */
10635    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10636            PackageParser.Package scannedPackage) {
10637        String requiredInstructionSet = null;
10638        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10639            requiredInstructionSet = VMRuntime.getInstructionSet(
10640                     scannedPackage.applicationInfo.primaryCpuAbi);
10641        }
10642
10643        PackageSetting requirer = null;
10644        for (PackageSetting ps : packagesForUser) {
10645            // If packagesForUser contains scannedPackage, we skip it. This will happen
10646            // when scannedPackage is an update of an existing package. Without this check,
10647            // we will never be able to change the ABI of any package belonging to a shared
10648            // user, even if it's compatible with other packages.
10649            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10650                if (ps.primaryCpuAbiString == null) {
10651                    continue;
10652                }
10653
10654                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10655                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10656                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10657                    // this but there's not much we can do.
10658                    String errorMessage = "Instruction set mismatch, "
10659                            + ((requirer == null) ? "[caller]" : requirer)
10660                            + " requires " + requiredInstructionSet + " whereas " + ps
10661                            + " requires " + instructionSet;
10662                    Slog.w(TAG, errorMessage);
10663                }
10664
10665                if (requiredInstructionSet == null) {
10666                    requiredInstructionSet = instructionSet;
10667                    requirer = ps;
10668                }
10669            }
10670        }
10671
10672        if (requiredInstructionSet != null) {
10673            String adjustedAbi;
10674            if (requirer != null) {
10675                // requirer != null implies that either scannedPackage was null or that scannedPackage
10676                // did not require an ABI, in which case we have to adjust scannedPackage to match
10677                // the ABI of the set (which is the same as requirer's ABI)
10678                adjustedAbi = requirer.primaryCpuAbiString;
10679                if (scannedPackage != null) {
10680                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10681                }
10682            } else {
10683                // requirer == null implies that we're updating all ABIs in the set to
10684                // match scannedPackage.
10685                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10686            }
10687
10688            for (PackageSetting ps : packagesForUser) {
10689                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10690                    if (ps.primaryCpuAbiString != null) {
10691                        continue;
10692                    }
10693
10694                    ps.primaryCpuAbiString = adjustedAbi;
10695                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10696                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10697                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10698                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10699                                + " (requirer="
10700                                + (requirer != null ? requirer.pkg : "null")
10701                                + ", scannedPackage="
10702                                + (scannedPackage != null ? scannedPackage : "null")
10703                                + ")");
10704                        try {
10705                            mInstaller.rmdex(ps.codePathString,
10706                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10707                        } catch (InstallerException ignored) {
10708                        }
10709                    }
10710                }
10711            }
10712        }
10713    }
10714
10715    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10716        synchronized (mPackages) {
10717            mResolverReplaced = true;
10718            // Set up information for custom user intent resolution activity.
10719            mResolveActivity.applicationInfo = pkg.applicationInfo;
10720            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10721            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10722            mResolveActivity.processName = pkg.applicationInfo.packageName;
10723            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10724            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10725                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10726            mResolveActivity.theme = 0;
10727            mResolveActivity.exported = true;
10728            mResolveActivity.enabled = true;
10729            mResolveInfo.activityInfo = mResolveActivity;
10730            mResolveInfo.priority = 0;
10731            mResolveInfo.preferredOrder = 0;
10732            mResolveInfo.match = 0;
10733            mResolveComponentName = mCustomResolverComponentName;
10734            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10735                    mResolveComponentName);
10736        }
10737    }
10738
10739    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10740        if (installerActivity == null) {
10741            if (DEBUG_EPHEMERAL) {
10742                Slog.d(TAG, "Clear ephemeral installer activity");
10743            }
10744            mInstantAppInstallerActivity = null;
10745            return;
10746        }
10747
10748        if (DEBUG_EPHEMERAL) {
10749            Slog.d(TAG, "Set ephemeral installer activity: "
10750                    + installerActivity.getComponentName());
10751        }
10752        // Set up information for ephemeral installer activity
10753        mInstantAppInstallerActivity = installerActivity;
10754        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10755                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10756        mInstantAppInstallerActivity.exported = true;
10757        mInstantAppInstallerActivity.enabled = true;
10758        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10759        mInstantAppInstallerInfo.priority = 0;
10760        mInstantAppInstallerInfo.preferredOrder = 1;
10761        mInstantAppInstallerInfo.isDefault = true;
10762        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10763                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10764    }
10765
10766    private static String calculateBundledApkRoot(final String codePathString) {
10767        final File codePath = new File(codePathString);
10768        final File codeRoot;
10769        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10770            codeRoot = Environment.getRootDirectory();
10771        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10772            codeRoot = Environment.getOemDirectory();
10773        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10774            codeRoot = Environment.getVendorDirectory();
10775        } else {
10776            // Unrecognized code path; take its top real segment as the apk root:
10777            // e.g. /something/app/blah.apk => /something
10778            try {
10779                File f = codePath.getCanonicalFile();
10780                File parent = f.getParentFile();    // non-null because codePath is a file
10781                File tmp;
10782                while ((tmp = parent.getParentFile()) != null) {
10783                    f = parent;
10784                    parent = tmp;
10785                }
10786                codeRoot = f;
10787                Slog.w(TAG, "Unrecognized code path "
10788                        + codePath + " - using " + codeRoot);
10789            } catch (IOException e) {
10790                // Can't canonicalize the code path -- shenanigans?
10791                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10792                return Environment.getRootDirectory().getPath();
10793            }
10794        }
10795        return codeRoot.getPath();
10796    }
10797
10798    /**
10799     * Derive and set the location of native libraries for the given package,
10800     * which varies depending on where and how the package was installed.
10801     */
10802    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10803        final ApplicationInfo info = pkg.applicationInfo;
10804        final String codePath = pkg.codePath;
10805        final File codeFile = new File(codePath);
10806        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10807        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10808
10809        info.nativeLibraryRootDir = null;
10810        info.nativeLibraryRootRequiresIsa = false;
10811        info.nativeLibraryDir = null;
10812        info.secondaryNativeLibraryDir = null;
10813
10814        if (isApkFile(codeFile)) {
10815            // Monolithic install
10816            if (bundledApp) {
10817                // If "/system/lib64/apkname" exists, assume that is the per-package
10818                // native library directory to use; otherwise use "/system/lib/apkname".
10819                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10820                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10821                        getPrimaryInstructionSet(info));
10822
10823                // This is a bundled system app so choose the path based on the ABI.
10824                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10825                // is just the default path.
10826                final String apkName = deriveCodePathName(codePath);
10827                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10828                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10829                        apkName).getAbsolutePath();
10830
10831                if (info.secondaryCpuAbi != null) {
10832                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10833                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10834                            secondaryLibDir, apkName).getAbsolutePath();
10835                }
10836            } else if (asecApp) {
10837                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10838                        .getAbsolutePath();
10839            } else {
10840                final String apkName = deriveCodePathName(codePath);
10841                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10842                        .getAbsolutePath();
10843            }
10844
10845            info.nativeLibraryRootRequiresIsa = false;
10846            info.nativeLibraryDir = info.nativeLibraryRootDir;
10847        } else {
10848            // Cluster install
10849            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10850            info.nativeLibraryRootRequiresIsa = true;
10851
10852            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10853                    getPrimaryInstructionSet(info)).getAbsolutePath();
10854
10855            if (info.secondaryCpuAbi != null) {
10856                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10857                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10858            }
10859        }
10860    }
10861
10862    /**
10863     * Calculate the abis and roots for a bundled app. These can uniquely
10864     * be determined from the contents of the system partition, i.e whether
10865     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10866     * of this information, and instead assume that the system was built
10867     * sensibly.
10868     */
10869    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10870                                           PackageSetting pkgSetting) {
10871        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10872
10873        // If "/system/lib64/apkname" exists, assume that is the per-package
10874        // native library directory to use; otherwise use "/system/lib/apkname".
10875        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10876        setBundledAppAbi(pkg, apkRoot, apkName);
10877        // pkgSetting might be null during rescan following uninstall of updates
10878        // to a bundled app, so accommodate that possibility.  The settings in
10879        // that case will be established later from the parsed package.
10880        //
10881        // If the settings aren't null, sync them up with what we've just derived.
10882        // note that apkRoot isn't stored in the package settings.
10883        if (pkgSetting != null) {
10884            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10885            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10886        }
10887    }
10888
10889    /**
10890     * Deduces the ABI of a bundled app and sets the relevant fields on the
10891     * parsed pkg object.
10892     *
10893     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10894     *        under which system libraries are installed.
10895     * @param apkName the name of the installed package.
10896     */
10897    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10898        final File codeFile = new File(pkg.codePath);
10899
10900        final boolean has64BitLibs;
10901        final boolean has32BitLibs;
10902        if (isApkFile(codeFile)) {
10903            // Monolithic install
10904            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10905            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10906        } else {
10907            // Cluster install
10908            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10909            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10910                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10911                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10912                has64BitLibs = (new File(rootDir, isa)).exists();
10913            } else {
10914                has64BitLibs = false;
10915            }
10916            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10917                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10918                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10919                has32BitLibs = (new File(rootDir, isa)).exists();
10920            } else {
10921                has32BitLibs = false;
10922            }
10923        }
10924
10925        if (has64BitLibs && !has32BitLibs) {
10926            // The package has 64 bit libs, but not 32 bit libs. Its primary
10927            // ABI should be 64 bit. We can safely assume here that the bundled
10928            // native libraries correspond to the most preferred ABI in the list.
10929
10930            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10931            pkg.applicationInfo.secondaryCpuAbi = null;
10932        } else if (has32BitLibs && !has64BitLibs) {
10933            // The package has 32 bit libs but not 64 bit libs. Its primary
10934            // ABI should be 32 bit.
10935
10936            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10937            pkg.applicationInfo.secondaryCpuAbi = null;
10938        } else if (has32BitLibs && has64BitLibs) {
10939            // The application has both 64 and 32 bit bundled libraries. We check
10940            // here that the app declares multiArch support, and warn if it doesn't.
10941            //
10942            // We will be lenient here and record both ABIs. The primary will be the
10943            // ABI that's higher on the list, i.e, a device that's configured to prefer
10944            // 64 bit apps will see a 64 bit primary ABI,
10945
10946            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10947                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10948            }
10949
10950            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10951                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10952                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10953            } else {
10954                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10955                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10956            }
10957        } else {
10958            pkg.applicationInfo.primaryCpuAbi = null;
10959            pkg.applicationInfo.secondaryCpuAbi = null;
10960        }
10961    }
10962
10963    private void killApplication(String pkgName, int appId, String reason) {
10964        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10965    }
10966
10967    private void killApplication(String pkgName, int appId, int userId, String reason) {
10968        // Request the ActivityManager to kill the process(only for existing packages)
10969        // so that we do not end up in a confused state while the user is still using the older
10970        // version of the application while the new one gets installed.
10971        final long token = Binder.clearCallingIdentity();
10972        try {
10973            IActivityManager am = ActivityManager.getService();
10974            if (am != null) {
10975                try {
10976                    am.killApplication(pkgName, appId, userId, reason);
10977                } catch (RemoteException e) {
10978                }
10979            }
10980        } finally {
10981            Binder.restoreCallingIdentity(token);
10982        }
10983    }
10984
10985    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10986        // Remove the parent package setting
10987        PackageSetting ps = (PackageSetting) pkg.mExtras;
10988        if (ps != null) {
10989            removePackageLI(ps, chatty);
10990        }
10991        // Remove the child package setting
10992        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10993        for (int i = 0; i < childCount; i++) {
10994            PackageParser.Package childPkg = pkg.childPackages.get(i);
10995            ps = (PackageSetting) childPkg.mExtras;
10996            if (ps != null) {
10997                removePackageLI(ps, chatty);
10998            }
10999        }
11000    }
11001
11002    void removePackageLI(PackageSetting ps, boolean chatty) {
11003        if (DEBUG_INSTALL) {
11004            if (chatty)
11005                Log.d(TAG, "Removing package " + ps.name);
11006        }
11007
11008        // writer
11009        synchronized (mPackages) {
11010            mPackages.remove(ps.name);
11011            final PackageParser.Package pkg = ps.pkg;
11012            if (pkg != null) {
11013                cleanPackageDataStructuresLILPw(pkg, chatty);
11014            }
11015        }
11016    }
11017
11018    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11019        if (DEBUG_INSTALL) {
11020            if (chatty)
11021                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11022        }
11023
11024        // writer
11025        synchronized (mPackages) {
11026            // Remove the parent package
11027            mPackages.remove(pkg.applicationInfo.packageName);
11028            cleanPackageDataStructuresLILPw(pkg, chatty);
11029
11030            // Remove the child packages
11031            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11032            for (int i = 0; i < childCount; i++) {
11033                PackageParser.Package childPkg = pkg.childPackages.get(i);
11034                mPackages.remove(childPkg.applicationInfo.packageName);
11035                cleanPackageDataStructuresLILPw(childPkg, chatty);
11036            }
11037        }
11038    }
11039
11040    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11041        int N = pkg.providers.size();
11042        StringBuilder r = null;
11043        int i;
11044        for (i=0; i<N; i++) {
11045            PackageParser.Provider p = pkg.providers.get(i);
11046            mProviders.removeProvider(p);
11047            if (p.info.authority == null) {
11048
11049                /* There was another ContentProvider with this authority when
11050                 * this app was installed so this authority is null,
11051                 * Ignore it as we don't have to unregister the provider.
11052                 */
11053                continue;
11054            }
11055            String names[] = p.info.authority.split(";");
11056            for (int j = 0; j < names.length; j++) {
11057                if (mProvidersByAuthority.get(names[j]) == p) {
11058                    mProvidersByAuthority.remove(names[j]);
11059                    if (DEBUG_REMOVE) {
11060                        if (chatty)
11061                            Log.d(TAG, "Unregistered content provider: " + names[j]
11062                                    + ", className = " + p.info.name + ", isSyncable = "
11063                                    + p.info.isSyncable);
11064                    }
11065                }
11066            }
11067            if (DEBUG_REMOVE && chatty) {
11068                if (r == null) {
11069                    r = new StringBuilder(256);
11070                } else {
11071                    r.append(' ');
11072                }
11073                r.append(p.info.name);
11074            }
11075        }
11076        if (r != null) {
11077            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11078        }
11079
11080        N = pkg.services.size();
11081        r = null;
11082        for (i=0; i<N; i++) {
11083            PackageParser.Service s = pkg.services.get(i);
11084            mServices.removeService(s);
11085            if (chatty) {
11086                if (r == null) {
11087                    r = new StringBuilder(256);
11088                } else {
11089                    r.append(' ');
11090                }
11091                r.append(s.info.name);
11092            }
11093        }
11094        if (r != null) {
11095            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11096        }
11097
11098        N = pkg.receivers.size();
11099        r = null;
11100        for (i=0; i<N; i++) {
11101            PackageParser.Activity a = pkg.receivers.get(i);
11102            mReceivers.removeActivity(a, "receiver");
11103            if (DEBUG_REMOVE && chatty) {
11104                if (r == null) {
11105                    r = new StringBuilder(256);
11106                } else {
11107                    r.append(' ');
11108                }
11109                r.append(a.info.name);
11110            }
11111        }
11112        if (r != null) {
11113            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11114        }
11115
11116        N = pkg.activities.size();
11117        r = null;
11118        for (i=0; i<N; i++) {
11119            PackageParser.Activity a = pkg.activities.get(i);
11120            mActivities.removeActivity(a, "activity");
11121            if (DEBUG_REMOVE && chatty) {
11122                if (r == null) {
11123                    r = new StringBuilder(256);
11124                } else {
11125                    r.append(' ');
11126                }
11127                r.append(a.info.name);
11128            }
11129        }
11130        if (r != null) {
11131            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11132        }
11133
11134        N = pkg.permissions.size();
11135        r = null;
11136        for (i=0; i<N; i++) {
11137            PackageParser.Permission p = pkg.permissions.get(i);
11138            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11139            if (bp == null) {
11140                bp = mSettings.mPermissionTrees.get(p.info.name);
11141            }
11142            if (bp != null && bp.perm == p) {
11143                bp.perm = null;
11144                if (DEBUG_REMOVE && chatty) {
11145                    if (r == null) {
11146                        r = new StringBuilder(256);
11147                    } else {
11148                        r.append(' ');
11149                    }
11150                    r.append(p.info.name);
11151                }
11152            }
11153            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11154                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11155                if (appOpPkgs != null) {
11156                    appOpPkgs.remove(pkg.packageName);
11157                }
11158            }
11159        }
11160        if (r != null) {
11161            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11162        }
11163
11164        N = pkg.requestedPermissions.size();
11165        r = null;
11166        for (i=0; i<N; i++) {
11167            String perm = pkg.requestedPermissions.get(i);
11168            BasePermission bp = mSettings.mPermissions.get(perm);
11169            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11170                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11171                if (appOpPkgs != null) {
11172                    appOpPkgs.remove(pkg.packageName);
11173                    if (appOpPkgs.isEmpty()) {
11174                        mAppOpPermissionPackages.remove(perm);
11175                    }
11176                }
11177            }
11178        }
11179        if (r != null) {
11180            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11181        }
11182
11183        N = pkg.instrumentation.size();
11184        r = null;
11185        for (i=0; i<N; i++) {
11186            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11187            mInstrumentation.remove(a.getComponentName());
11188            if (DEBUG_REMOVE && chatty) {
11189                if (r == null) {
11190                    r = new StringBuilder(256);
11191                } else {
11192                    r.append(' ');
11193                }
11194                r.append(a.info.name);
11195            }
11196        }
11197        if (r != null) {
11198            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11199        }
11200
11201        r = null;
11202        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11203            // Only system apps can hold shared libraries.
11204            if (pkg.libraryNames != null) {
11205                for (i = 0; i < pkg.libraryNames.size(); i++) {
11206                    String name = pkg.libraryNames.get(i);
11207                    if (removeSharedLibraryLPw(name, 0)) {
11208                        if (DEBUG_REMOVE && chatty) {
11209                            if (r == null) {
11210                                r = new StringBuilder(256);
11211                            } else {
11212                                r.append(' ');
11213                            }
11214                            r.append(name);
11215                        }
11216                    }
11217                }
11218            }
11219        }
11220
11221        r = null;
11222
11223        // Any package can hold static shared libraries.
11224        if (pkg.staticSharedLibName != null) {
11225            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11226                if (DEBUG_REMOVE && chatty) {
11227                    if (r == null) {
11228                        r = new StringBuilder(256);
11229                    } else {
11230                        r.append(' ');
11231                    }
11232                    r.append(pkg.staticSharedLibName);
11233                }
11234            }
11235        }
11236
11237        if (r != null) {
11238            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11239        }
11240    }
11241
11242    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11243        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11244            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11245                return true;
11246            }
11247        }
11248        return false;
11249    }
11250
11251    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11252    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11253    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11254
11255    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11256        // Update the parent permissions
11257        updatePermissionsLPw(pkg.packageName, pkg, flags);
11258        // Update the child permissions
11259        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11260        for (int i = 0; i < childCount; i++) {
11261            PackageParser.Package childPkg = pkg.childPackages.get(i);
11262            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11263        }
11264    }
11265
11266    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11267            int flags) {
11268        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11269        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11270    }
11271
11272    private void updatePermissionsLPw(String changingPkg,
11273            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11274        // Make sure there are no dangling permission trees.
11275        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11276        while (it.hasNext()) {
11277            final BasePermission bp = it.next();
11278            if (bp.packageSetting == null) {
11279                // We may not yet have parsed the package, so just see if
11280                // we still know about its settings.
11281                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11282            }
11283            if (bp.packageSetting == null) {
11284                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11285                        + " from package " + bp.sourcePackage);
11286                it.remove();
11287            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11288                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11289                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11290                            + " from package " + bp.sourcePackage);
11291                    flags |= UPDATE_PERMISSIONS_ALL;
11292                    it.remove();
11293                }
11294            }
11295        }
11296
11297        // Make sure all dynamic permissions have been assigned to a package,
11298        // and make sure there are no dangling permissions.
11299        it = mSettings.mPermissions.values().iterator();
11300        while (it.hasNext()) {
11301            final BasePermission bp = it.next();
11302            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11303                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11304                        + bp.name + " pkg=" + bp.sourcePackage
11305                        + " info=" + bp.pendingInfo);
11306                if (bp.packageSetting == null && bp.pendingInfo != null) {
11307                    final BasePermission tree = findPermissionTreeLP(bp.name);
11308                    if (tree != null && tree.perm != null) {
11309                        bp.packageSetting = tree.packageSetting;
11310                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11311                                new PermissionInfo(bp.pendingInfo));
11312                        bp.perm.info.packageName = tree.perm.info.packageName;
11313                        bp.perm.info.name = bp.name;
11314                        bp.uid = tree.uid;
11315                    }
11316                }
11317            }
11318            if (bp.packageSetting == null) {
11319                // We may not yet have parsed the package, so just see if
11320                // we still know about its settings.
11321                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11322            }
11323            if (bp.packageSetting == null) {
11324                Slog.w(TAG, "Removing dangling permission: " + bp.name
11325                        + " from package " + bp.sourcePackage);
11326                it.remove();
11327            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11328                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11329                    Slog.i(TAG, "Removing old permission: " + bp.name
11330                            + " from package " + bp.sourcePackage);
11331                    flags |= UPDATE_PERMISSIONS_ALL;
11332                    it.remove();
11333                }
11334            }
11335        }
11336
11337        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11338        // Now update the permissions for all packages, in particular
11339        // replace the granted permissions of the system packages.
11340        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11341            for (PackageParser.Package pkg : mPackages.values()) {
11342                if (pkg != pkgInfo) {
11343                    // Only replace for packages on requested volume
11344                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11345                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11346                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11347                    grantPermissionsLPw(pkg, replace, changingPkg);
11348                }
11349            }
11350        }
11351
11352        if (pkgInfo != null) {
11353            // Only replace for packages on requested volume
11354            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11355            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11356                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11357            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11358        }
11359        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11360    }
11361
11362    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11363            String packageOfInterest) {
11364        // IMPORTANT: There are two types of permissions: install and runtime.
11365        // Install time permissions are granted when the app is installed to
11366        // all device users and users added in the future. Runtime permissions
11367        // are granted at runtime explicitly to specific users. Normal and signature
11368        // protected permissions are install time permissions. Dangerous permissions
11369        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11370        // otherwise they are runtime permissions. This function does not manage
11371        // runtime permissions except for the case an app targeting Lollipop MR1
11372        // being upgraded to target a newer SDK, in which case dangerous permissions
11373        // are transformed from install time to runtime ones.
11374
11375        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11376        if (ps == null) {
11377            return;
11378        }
11379
11380        PermissionsState permissionsState = ps.getPermissionsState();
11381        PermissionsState origPermissions = permissionsState;
11382
11383        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11384
11385        boolean runtimePermissionsRevoked = false;
11386        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11387
11388        boolean changedInstallPermission = false;
11389
11390        if (replace) {
11391            ps.installPermissionsFixed = false;
11392            if (!ps.isSharedUser()) {
11393                origPermissions = new PermissionsState(permissionsState);
11394                permissionsState.reset();
11395            } else {
11396                // We need to know only about runtime permission changes since the
11397                // calling code always writes the install permissions state but
11398                // the runtime ones are written only if changed. The only cases of
11399                // changed runtime permissions here are promotion of an install to
11400                // runtime and revocation of a runtime from a shared user.
11401                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11402                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11403                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11404                    runtimePermissionsRevoked = true;
11405                }
11406            }
11407        }
11408
11409        permissionsState.setGlobalGids(mGlobalGids);
11410
11411        final int N = pkg.requestedPermissions.size();
11412        for (int i=0; i<N; i++) {
11413            final String name = pkg.requestedPermissions.get(i);
11414            final BasePermission bp = mSettings.mPermissions.get(name);
11415
11416            if (DEBUG_INSTALL) {
11417                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11418            }
11419
11420            if (bp == null || bp.packageSetting == null) {
11421                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11422                    Slog.w(TAG, "Unknown permission " + name
11423                            + " in package " + pkg.packageName);
11424                }
11425                continue;
11426            }
11427
11428
11429            // Limit ephemeral apps to ephemeral allowed permissions.
11430            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11431                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11432                        + pkg.packageName);
11433                continue;
11434            }
11435
11436            final String perm = bp.name;
11437            boolean allowedSig = false;
11438            int grant = GRANT_DENIED;
11439
11440            // Keep track of app op permissions.
11441            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11442                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11443                if (pkgs == null) {
11444                    pkgs = new ArraySet<>();
11445                    mAppOpPermissionPackages.put(bp.name, pkgs);
11446                }
11447                pkgs.add(pkg.packageName);
11448            }
11449
11450            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11451            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11452                    >= Build.VERSION_CODES.M;
11453            switch (level) {
11454                case PermissionInfo.PROTECTION_NORMAL: {
11455                    // For all apps normal permissions are install time ones.
11456                    grant = GRANT_INSTALL;
11457                } break;
11458
11459                case PermissionInfo.PROTECTION_DANGEROUS: {
11460                    // If a permission review is required for legacy apps we represent
11461                    // their permissions as always granted runtime ones since we need
11462                    // to keep the review required permission flag per user while an
11463                    // install permission's state is shared across all users.
11464                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11465                        // For legacy apps dangerous permissions are install time ones.
11466                        grant = GRANT_INSTALL;
11467                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11468                        // For legacy apps that became modern, install becomes runtime.
11469                        grant = GRANT_UPGRADE;
11470                    } else if (mPromoteSystemApps
11471                            && isSystemApp(ps)
11472                            && mExistingSystemPackages.contains(ps.name)) {
11473                        // For legacy system apps, install becomes runtime.
11474                        // We cannot check hasInstallPermission() for system apps since those
11475                        // permissions were granted implicitly and not persisted pre-M.
11476                        grant = GRANT_UPGRADE;
11477                    } else {
11478                        // For modern apps keep runtime permissions unchanged.
11479                        grant = GRANT_RUNTIME;
11480                    }
11481                } break;
11482
11483                case PermissionInfo.PROTECTION_SIGNATURE: {
11484                    // For all apps signature permissions are install time ones.
11485                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11486                    if (allowedSig) {
11487                        grant = GRANT_INSTALL;
11488                    }
11489                } break;
11490            }
11491
11492            if (DEBUG_INSTALL) {
11493                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11494            }
11495
11496            if (grant != GRANT_DENIED) {
11497                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11498                    // If this is an existing, non-system package, then
11499                    // we can't add any new permissions to it.
11500                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11501                        // Except...  if this is a permission that was added
11502                        // to the platform (note: need to only do this when
11503                        // updating the platform).
11504                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11505                            grant = GRANT_DENIED;
11506                        }
11507                    }
11508                }
11509
11510                switch (grant) {
11511                    case GRANT_INSTALL: {
11512                        // Revoke this as runtime permission to handle the case of
11513                        // a runtime permission being downgraded to an install one.
11514                        // Also in permission review mode we keep dangerous permissions
11515                        // for legacy apps
11516                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11517                            if (origPermissions.getRuntimePermissionState(
11518                                    bp.name, userId) != null) {
11519                                // Revoke the runtime permission and clear the flags.
11520                                origPermissions.revokeRuntimePermission(bp, userId);
11521                                origPermissions.updatePermissionFlags(bp, userId,
11522                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11523                                // If we revoked a permission permission, we have to write.
11524                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11525                                        changedRuntimePermissionUserIds, userId);
11526                            }
11527                        }
11528                        // Grant an install permission.
11529                        if (permissionsState.grantInstallPermission(bp) !=
11530                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11531                            changedInstallPermission = true;
11532                        }
11533                    } break;
11534
11535                    case GRANT_RUNTIME: {
11536                        // Grant previously granted runtime permissions.
11537                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11538                            PermissionState permissionState = origPermissions
11539                                    .getRuntimePermissionState(bp.name, userId);
11540                            int flags = permissionState != null
11541                                    ? permissionState.getFlags() : 0;
11542                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11543                                // Don't propagate the permission in a permission review mode if
11544                                // the former was revoked, i.e. marked to not propagate on upgrade.
11545                                // Note that in a permission review mode install permissions are
11546                                // represented as constantly granted runtime ones since we need to
11547                                // keep a per user state associated with the permission. Also the
11548                                // revoke on upgrade flag is no longer applicable and is reset.
11549                                final boolean revokeOnUpgrade = (flags & PackageManager
11550                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11551                                if (revokeOnUpgrade) {
11552                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11553                                    // Since we changed the flags, we have to write.
11554                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11555                                            changedRuntimePermissionUserIds, userId);
11556                                }
11557                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11558                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11559                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11560                                        // If we cannot put the permission as it was,
11561                                        // we have to write.
11562                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11563                                                changedRuntimePermissionUserIds, userId);
11564                                    }
11565                                }
11566
11567                                // If the app supports runtime permissions no need for a review.
11568                                if (mPermissionReviewRequired
11569                                        && appSupportsRuntimePermissions
11570                                        && (flags & PackageManager
11571                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11572                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11573                                    // Since we changed the flags, we have to write.
11574                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11575                                            changedRuntimePermissionUserIds, userId);
11576                                }
11577                            } else if (mPermissionReviewRequired
11578                                    && !appSupportsRuntimePermissions) {
11579                                // For legacy apps that need a permission review, every new
11580                                // runtime permission is granted but it is pending a review.
11581                                // We also need to review only platform defined runtime
11582                                // permissions as these are the only ones the platform knows
11583                                // how to disable the API to simulate revocation as legacy
11584                                // apps don't expect to run with revoked permissions.
11585                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11586                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11587                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11588                                        // We changed the flags, hence have to write.
11589                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11590                                                changedRuntimePermissionUserIds, userId);
11591                                    }
11592                                }
11593                                if (permissionsState.grantRuntimePermission(bp, userId)
11594                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11595                                    // We changed the permission, hence have to write.
11596                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11597                                            changedRuntimePermissionUserIds, userId);
11598                                }
11599                            }
11600                            // Propagate the permission flags.
11601                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11602                        }
11603                    } break;
11604
11605                    case GRANT_UPGRADE: {
11606                        // Grant runtime permissions for a previously held install permission.
11607                        PermissionState permissionState = origPermissions
11608                                .getInstallPermissionState(bp.name);
11609                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11610
11611                        if (origPermissions.revokeInstallPermission(bp)
11612                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11613                            // We will be transferring the permission flags, so clear them.
11614                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11615                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11616                            changedInstallPermission = true;
11617                        }
11618
11619                        // If the permission is not to be promoted to runtime we ignore it and
11620                        // also its other flags as they are not applicable to install permissions.
11621                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11622                            for (int userId : currentUserIds) {
11623                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11624                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11625                                    // Transfer the permission flags.
11626                                    permissionsState.updatePermissionFlags(bp, userId,
11627                                            flags, flags);
11628                                    // If we granted the permission, we have to write.
11629                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11630                                            changedRuntimePermissionUserIds, userId);
11631                                }
11632                            }
11633                        }
11634                    } break;
11635
11636                    default: {
11637                        if (packageOfInterest == null
11638                                || packageOfInterest.equals(pkg.packageName)) {
11639                            Slog.w(TAG, "Not granting permission " + perm
11640                                    + " to package " + pkg.packageName
11641                                    + " because it was previously installed without");
11642                        }
11643                    } break;
11644                }
11645            } else {
11646                if (permissionsState.revokeInstallPermission(bp) !=
11647                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11648                    // Also drop the permission flags.
11649                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11650                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11651                    changedInstallPermission = true;
11652                    Slog.i(TAG, "Un-granting permission " + perm
11653                            + " from package " + pkg.packageName
11654                            + " (protectionLevel=" + bp.protectionLevel
11655                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11656                            + ")");
11657                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11658                    // Don't print warning for app op permissions, since it is fine for them
11659                    // not to be granted, there is a UI for the user to decide.
11660                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11661                        Slog.w(TAG, "Not granting permission " + perm
11662                                + " to package " + pkg.packageName
11663                                + " (protectionLevel=" + bp.protectionLevel
11664                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11665                                + ")");
11666                    }
11667                }
11668            }
11669        }
11670
11671        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11672                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11673            // This is the first that we have heard about this package, so the
11674            // permissions we have now selected are fixed until explicitly
11675            // changed.
11676            ps.installPermissionsFixed = true;
11677        }
11678
11679        // Persist the runtime permissions state for users with changes. If permissions
11680        // were revoked because no app in the shared user declares them we have to
11681        // write synchronously to avoid losing runtime permissions state.
11682        for (int userId : changedRuntimePermissionUserIds) {
11683            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11684        }
11685    }
11686
11687    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11688        boolean allowed = false;
11689        final int NP = PackageParser.NEW_PERMISSIONS.length;
11690        for (int ip=0; ip<NP; ip++) {
11691            final PackageParser.NewPermissionInfo npi
11692                    = PackageParser.NEW_PERMISSIONS[ip];
11693            if (npi.name.equals(perm)
11694                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11695                allowed = true;
11696                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11697                        + pkg.packageName);
11698                break;
11699            }
11700        }
11701        return allowed;
11702    }
11703
11704    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11705            BasePermission bp, PermissionsState origPermissions) {
11706        boolean privilegedPermission = (bp.protectionLevel
11707                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11708        boolean privappPermissionsDisable =
11709                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11710        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11711        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11712        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11713                && !platformPackage && platformPermission) {
11714            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11715                    .getPrivAppPermissions(pkg.packageName);
11716            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11717            if (!whitelisted) {
11718                Slog.w(TAG, "Privileged permission " + perm + " for package "
11719                        + pkg.packageName + " - not in privapp-permissions whitelist");
11720                // Only report violations for apps on system image
11721                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11722                    if (mPrivappPermissionsViolations == null) {
11723                        mPrivappPermissionsViolations = new ArraySet<>();
11724                    }
11725                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11726                }
11727                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11728                    return false;
11729                }
11730            }
11731        }
11732        boolean allowed = (compareSignatures(
11733                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11734                        == PackageManager.SIGNATURE_MATCH)
11735                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11736                        == PackageManager.SIGNATURE_MATCH);
11737        if (!allowed && privilegedPermission) {
11738            if (isSystemApp(pkg)) {
11739                // For updated system applications, a system permission
11740                // is granted only if it had been defined by the original application.
11741                if (pkg.isUpdatedSystemApp()) {
11742                    final PackageSetting sysPs = mSettings
11743                            .getDisabledSystemPkgLPr(pkg.packageName);
11744                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11745                        // If the original was granted this permission, we take
11746                        // that grant decision as read and propagate it to the
11747                        // update.
11748                        if (sysPs.isPrivileged()) {
11749                            allowed = true;
11750                        }
11751                    } else {
11752                        // The system apk may have been updated with an older
11753                        // version of the one on the data partition, but which
11754                        // granted a new system permission that it didn't have
11755                        // before.  In this case we do want to allow the app to
11756                        // now get the new permission if the ancestral apk is
11757                        // privileged to get it.
11758                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11759                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11760                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11761                                    allowed = true;
11762                                    break;
11763                                }
11764                            }
11765                        }
11766                        // Also if a privileged parent package on the system image or any of
11767                        // its children requested a privileged permission, the updated child
11768                        // packages can also get the permission.
11769                        if (pkg.parentPackage != null) {
11770                            final PackageSetting disabledSysParentPs = mSettings
11771                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11772                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11773                                    && disabledSysParentPs.isPrivileged()) {
11774                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11775                                    allowed = true;
11776                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11777                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11778                                    for (int i = 0; i < count; i++) {
11779                                        PackageParser.Package disabledSysChildPkg =
11780                                                disabledSysParentPs.pkg.childPackages.get(i);
11781                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11782                                                perm)) {
11783                                            allowed = true;
11784                                            break;
11785                                        }
11786                                    }
11787                                }
11788                            }
11789                        }
11790                    }
11791                } else {
11792                    allowed = isPrivilegedApp(pkg);
11793                }
11794            }
11795        }
11796        if (!allowed) {
11797            if (!allowed && (bp.protectionLevel
11798                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11799                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11800                // If this was a previously normal/dangerous permission that got moved
11801                // to a system permission as part of the runtime permission redesign, then
11802                // we still want to blindly grant it to old apps.
11803                allowed = true;
11804            }
11805            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11806                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11807                // If this permission is to be granted to the system installer and
11808                // this app is an installer, then it gets the permission.
11809                allowed = true;
11810            }
11811            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11812                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11813                // If this permission is to be granted to the system verifier and
11814                // this app is a verifier, then it gets the permission.
11815                allowed = true;
11816            }
11817            if (!allowed && (bp.protectionLevel
11818                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11819                    && isSystemApp(pkg)) {
11820                // Any pre-installed system app is allowed to get this permission.
11821                allowed = true;
11822            }
11823            if (!allowed && (bp.protectionLevel
11824                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11825                // For development permissions, a development permission
11826                // is granted only if it was already granted.
11827                allowed = origPermissions.hasInstallPermission(perm);
11828            }
11829            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11830                    && pkg.packageName.equals(mSetupWizardPackage)) {
11831                // If this permission is to be granted to the system setup wizard and
11832                // this app is a setup wizard, then it gets the permission.
11833                allowed = true;
11834            }
11835        }
11836        return allowed;
11837    }
11838
11839    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11840        final int permCount = pkg.requestedPermissions.size();
11841        for (int j = 0; j < permCount; j++) {
11842            String requestedPermission = pkg.requestedPermissions.get(j);
11843            if (permission.equals(requestedPermission)) {
11844                return true;
11845            }
11846        }
11847        return false;
11848    }
11849
11850    final class ActivityIntentResolver
11851            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11852        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11853                boolean defaultOnly, int userId) {
11854            if (!sUserManager.exists(userId)) return null;
11855            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11856            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11857        }
11858
11859        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11860                int userId) {
11861            if (!sUserManager.exists(userId)) return null;
11862            mFlags = flags;
11863            return super.queryIntent(intent, resolvedType,
11864                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11865                    userId);
11866        }
11867
11868        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11869                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11870            if (!sUserManager.exists(userId)) return null;
11871            if (packageActivities == null) {
11872                return null;
11873            }
11874            mFlags = flags;
11875            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11876            final int N = packageActivities.size();
11877            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11878                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11879
11880            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11881            for (int i = 0; i < N; ++i) {
11882                intentFilters = packageActivities.get(i).intents;
11883                if (intentFilters != null && intentFilters.size() > 0) {
11884                    PackageParser.ActivityIntentInfo[] array =
11885                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11886                    intentFilters.toArray(array);
11887                    listCut.add(array);
11888                }
11889            }
11890            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11891        }
11892
11893        /**
11894         * Finds a privileged activity that matches the specified activity names.
11895         */
11896        private PackageParser.Activity findMatchingActivity(
11897                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11898            for (PackageParser.Activity sysActivity : activityList) {
11899                if (sysActivity.info.name.equals(activityInfo.name)) {
11900                    return sysActivity;
11901                }
11902                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11903                    return sysActivity;
11904                }
11905                if (sysActivity.info.targetActivity != null) {
11906                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11907                        return sysActivity;
11908                    }
11909                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11910                        return sysActivity;
11911                    }
11912                }
11913            }
11914            return null;
11915        }
11916
11917        public class IterGenerator<E> {
11918            public Iterator<E> generate(ActivityIntentInfo info) {
11919                return null;
11920            }
11921        }
11922
11923        public class ActionIterGenerator extends IterGenerator<String> {
11924            @Override
11925            public Iterator<String> generate(ActivityIntentInfo info) {
11926                return info.actionsIterator();
11927            }
11928        }
11929
11930        public class CategoriesIterGenerator extends IterGenerator<String> {
11931            @Override
11932            public Iterator<String> generate(ActivityIntentInfo info) {
11933                return info.categoriesIterator();
11934            }
11935        }
11936
11937        public class SchemesIterGenerator extends IterGenerator<String> {
11938            @Override
11939            public Iterator<String> generate(ActivityIntentInfo info) {
11940                return info.schemesIterator();
11941            }
11942        }
11943
11944        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11945            @Override
11946            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11947                return info.authoritiesIterator();
11948            }
11949        }
11950
11951        /**
11952         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11953         * MODIFIED. Do not pass in a list that should not be changed.
11954         */
11955        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11956                IterGenerator<T> generator, Iterator<T> searchIterator) {
11957            // loop through the set of actions; every one must be found in the intent filter
11958            while (searchIterator.hasNext()) {
11959                // we must have at least one filter in the list to consider a match
11960                if (intentList.size() == 0) {
11961                    break;
11962                }
11963
11964                final T searchAction = searchIterator.next();
11965
11966                // loop through the set of intent filters
11967                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11968                while (intentIter.hasNext()) {
11969                    final ActivityIntentInfo intentInfo = intentIter.next();
11970                    boolean selectionFound = false;
11971
11972                    // loop through the intent filter's selection criteria; at least one
11973                    // of them must match the searched criteria
11974                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11975                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11976                        final T intentSelection = intentSelectionIter.next();
11977                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11978                            selectionFound = true;
11979                            break;
11980                        }
11981                    }
11982
11983                    // the selection criteria wasn't found in this filter's set; this filter
11984                    // is not a potential match
11985                    if (!selectionFound) {
11986                        intentIter.remove();
11987                    }
11988                }
11989            }
11990        }
11991
11992        private boolean isProtectedAction(ActivityIntentInfo filter) {
11993            final Iterator<String> actionsIter = filter.actionsIterator();
11994            while (actionsIter != null && actionsIter.hasNext()) {
11995                final String filterAction = actionsIter.next();
11996                if (PROTECTED_ACTIONS.contains(filterAction)) {
11997                    return true;
11998                }
11999            }
12000            return false;
12001        }
12002
12003        /**
12004         * Adjusts the priority of the given intent filter according to policy.
12005         * <p>
12006         * <ul>
12007         * <li>The priority for non privileged applications is capped to '0'</li>
12008         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12009         * <li>The priority for unbundled updates to privileged applications is capped to the
12010         *      priority defined on the system partition</li>
12011         * </ul>
12012         * <p>
12013         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12014         * allowed to obtain any priority on any action.
12015         */
12016        private void adjustPriority(
12017                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12018            // nothing to do; priority is fine as-is
12019            if (intent.getPriority() <= 0) {
12020                return;
12021            }
12022
12023            final ActivityInfo activityInfo = intent.activity.info;
12024            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12025
12026            final boolean privilegedApp =
12027                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12028            if (!privilegedApp) {
12029                // non-privileged applications can never define a priority >0
12030                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12031                        + " package: " + applicationInfo.packageName
12032                        + " activity: " + intent.activity.className
12033                        + " origPrio: " + intent.getPriority());
12034                intent.setPriority(0);
12035                return;
12036            }
12037
12038            if (systemActivities == null) {
12039                // the system package is not disabled; we're parsing the system partition
12040                if (isProtectedAction(intent)) {
12041                    if (mDeferProtectedFilters) {
12042                        // We can't deal with these just yet. No component should ever obtain a
12043                        // >0 priority for a protected actions, with ONE exception -- the setup
12044                        // wizard. The setup wizard, however, cannot be known until we're able to
12045                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12046                        // until all intent filters have been processed. Chicken, meet egg.
12047                        // Let the filter temporarily have a high priority and rectify the
12048                        // priorities after all system packages have been scanned.
12049                        mProtectedFilters.add(intent);
12050                        if (DEBUG_FILTERS) {
12051                            Slog.i(TAG, "Protected action; save for later;"
12052                                    + " package: " + applicationInfo.packageName
12053                                    + " activity: " + intent.activity.className
12054                                    + " origPrio: " + intent.getPriority());
12055                        }
12056                        return;
12057                    } else {
12058                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12059                            Slog.i(TAG, "No setup wizard;"
12060                                + " All protected intents capped to priority 0");
12061                        }
12062                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12063                            if (DEBUG_FILTERS) {
12064                                Slog.i(TAG, "Found setup wizard;"
12065                                    + " allow priority " + intent.getPriority() + ";"
12066                                    + " package: " + intent.activity.info.packageName
12067                                    + " activity: " + intent.activity.className
12068                                    + " priority: " + intent.getPriority());
12069                            }
12070                            // setup wizard gets whatever it wants
12071                            return;
12072                        }
12073                        Slog.w(TAG, "Protected action; cap priority to 0;"
12074                                + " package: " + intent.activity.info.packageName
12075                                + " activity: " + intent.activity.className
12076                                + " origPrio: " + intent.getPriority());
12077                        intent.setPriority(0);
12078                        return;
12079                    }
12080                }
12081                // privileged apps on the system image get whatever priority they request
12082                return;
12083            }
12084
12085            // privileged app unbundled update ... try to find the same activity
12086            final PackageParser.Activity foundActivity =
12087                    findMatchingActivity(systemActivities, activityInfo);
12088            if (foundActivity == null) {
12089                // this is a new activity; it cannot obtain >0 priority
12090                if (DEBUG_FILTERS) {
12091                    Slog.i(TAG, "New activity; cap priority to 0;"
12092                            + " package: " + applicationInfo.packageName
12093                            + " activity: " + intent.activity.className
12094                            + " origPrio: " + intent.getPriority());
12095                }
12096                intent.setPriority(0);
12097                return;
12098            }
12099
12100            // found activity, now check for filter equivalence
12101
12102            // a shallow copy is enough; we modify the list, not its contents
12103            final List<ActivityIntentInfo> intentListCopy =
12104                    new ArrayList<>(foundActivity.intents);
12105            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12106
12107            // find matching action subsets
12108            final Iterator<String> actionsIterator = intent.actionsIterator();
12109            if (actionsIterator != null) {
12110                getIntentListSubset(
12111                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12112                if (intentListCopy.size() == 0) {
12113                    // no more intents to match; we're not equivalent
12114                    if (DEBUG_FILTERS) {
12115                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12116                                + " package: " + applicationInfo.packageName
12117                                + " activity: " + intent.activity.className
12118                                + " origPrio: " + intent.getPriority());
12119                    }
12120                    intent.setPriority(0);
12121                    return;
12122                }
12123            }
12124
12125            // find matching category subsets
12126            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12127            if (categoriesIterator != null) {
12128                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12129                        categoriesIterator);
12130                if (intentListCopy.size() == 0) {
12131                    // no more intents to match; we're not equivalent
12132                    if (DEBUG_FILTERS) {
12133                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12134                                + " package: " + applicationInfo.packageName
12135                                + " activity: " + intent.activity.className
12136                                + " origPrio: " + intent.getPriority());
12137                    }
12138                    intent.setPriority(0);
12139                    return;
12140                }
12141            }
12142
12143            // find matching schemes subsets
12144            final Iterator<String> schemesIterator = intent.schemesIterator();
12145            if (schemesIterator != null) {
12146                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12147                        schemesIterator);
12148                if (intentListCopy.size() == 0) {
12149                    // no more intents to match; we're not equivalent
12150                    if (DEBUG_FILTERS) {
12151                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12152                                + " package: " + applicationInfo.packageName
12153                                + " activity: " + intent.activity.className
12154                                + " origPrio: " + intent.getPriority());
12155                    }
12156                    intent.setPriority(0);
12157                    return;
12158                }
12159            }
12160
12161            // find matching authorities subsets
12162            final Iterator<IntentFilter.AuthorityEntry>
12163                    authoritiesIterator = intent.authoritiesIterator();
12164            if (authoritiesIterator != null) {
12165                getIntentListSubset(intentListCopy,
12166                        new AuthoritiesIterGenerator(),
12167                        authoritiesIterator);
12168                if (intentListCopy.size() == 0) {
12169                    // no more intents to match; we're not equivalent
12170                    if (DEBUG_FILTERS) {
12171                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12172                                + " package: " + applicationInfo.packageName
12173                                + " activity: " + intent.activity.className
12174                                + " origPrio: " + intent.getPriority());
12175                    }
12176                    intent.setPriority(0);
12177                    return;
12178                }
12179            }
12180
12181            // we found matching filter(s); app gets the max priority of all intents
12182            int cappedPriority = 0;
12183            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12184                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12185            }
12186            if (intent.getPriority() > cappedPriority) {
12187                if (DEBUG_FILTERS) {
12188                    Slog.i(TAG, "Found matching filter(s);"
12189                            + " cap priority to " + cappedPriority + ";"
12190                            + " package: " + applicationInfo.packageName
12191                            + " activity: " + intent.activity.className
12192                            + " origPrio: " + intent.getPriority());
12193                }
12194                intent.setPriority(cappedPriority);
12195                return;
12196            }
12197            // all this for nothing; the requested priority was <= what was on the system
12198        }
12199
12200        public final void addActivity(PackageParser.Activity a, String type) {
12201            mActivities.put(a.getComponentName(), a);
12202            if (DEBUG_SHOW_INFO)
12203                Log.v(
12204                TAG, "  " + type + " " +
12205                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12206            if (DEBUG_SHOW_INFO)
12207                Log.v(TAG, "    Class=" + a.info.name);
12208            final int NI = a.intents.size();
12209            for (int j=0; j<NI; j++) {
12210                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12211                if ("activity".equals(type)) {
12212                    final PackageSetting ps =
12213                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12214                    final List<PackageParser.Activity> systemActivities =
12215                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12216                    adjustPriority(systemActivities, intent);
12217                }
12218                if (DEBUG_SHOW_INFO) {
12219                    Log.v(TAG, "    IntentFilter:");
12220                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12221                }
12222                if (!intent.debugCheck()) {
12223                    Log.w(TAG, "==> For Activity " + a.info.name);
12224                }
12225                addFilter(intent);
12226            }
12227        }
12228
12229        public final void removeActivity(PackageParser.Activity a, String type) {
12230            mActivities.remove(a.getComponentName());
12231            if (DEBUG_SHOW_INFO) {
12232                Log.v(TAG, "  " + type + " "
12233                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12234                                : a.info.name) + ":");
12235                Log.v(TAG, "    Class=" + a.info.name);
12236            }
12237            final int NI = a.intents.size();
12238            for (int j=0; j<NI; j++) {
12239                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12240                if (DEBUG_SHOW_INFO) {
12241                    Log.v(TAG, "    IntentFilter:");
12242                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12243                }
12244                removeFilter(intent);
12245            }
12246        }
12247
12248        @Override
12249        protected boolean allowFilterResult(
12250                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12251            ActivityInfo filterAi = filter.activity.info;
12252            for (int i=dest.size()-1; i>=0; i--) {
12253                ActivityInfo destAi = dest.get(i).activityInfo;
12254                if (destAi.name == filterAi.name
12255                        && destAi.packageName == filterAi.packageName) {
12256                    return false;
12257                }
12258            }
12259            return true;
12260        }
12261
12262        @Override
12263        protected ActivityIntentInfo[] newArray(int size) {
12264            return new ActivityIntentInfo[size];
12265        }
12266
12267        @Override
12268        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12269            if (!sUserManager.exists(userId)) return true;
12270            PackageParser.Package p = filter.activity.owner;
12271            if (p != null) {
12272                PackageSetting ps = (PackageSetting)p.mExtras;
12273                if (ps != null) {
12274                    // System apps are never considered stopped for purposes of
12275                    // filtering, because there may be no way for the user to
12276                    // actually re-launch them.
12277                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12278                            && ps.getStopped(userId);
12279                }
12280            }
12281            return false;
12282        }
12283
12284        @Override
12285        protected boolean isPackageForFilter(String packageName,
12286                PackageParser.ActivityIntentInfo info) {
12287            return packageName.equals(info.activity.owner.packageName);
12288        }
12289
12290        @Override
12291        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12292                int match, int userId) {
12293            if (!sUserManager.exists(userId)) return null;
12294            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12295                return null;
12296            }
12297            final PackageParser.Activity activity = info.activity;
12298            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12299            if (ps == null) {
12300                return null;
12301            }
12302            final PackageUserState userState = ps.readUserState(userId);
12303            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12304                    userState, userId);
12305            if (ai == null) {
12306                return null;
12307            }
12308            final boolean matchVisibleToInstantApp =
12309                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12310            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12311            // throw out filters that aren't visible to ephemeral apps
12312            if (matchVisibleToInstantApp
12313                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12314                return null;
12315            }
12316            // throw out ephemeral filters if we're not explicitly requesting them
12317            if (!isInstantApp && userState.instantApp) {
12318                return null;
12319            }
12320            // throw out instant app filters if updates are available; will trigger
12321            // instant app resolution
12322            if (userState.instantApp && ps.isUpdateAvailable()) {
12323                return null;
12324            }
12325            final ResolveInfo res = new ResolveInfo();
12326            res.activityInfo = ai;
12327            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12328                res.filter = info;
12329            }
12330            if (info != null) {
12331                res.handleAllWebDataURI = info.handleAllWebDataURI();
12332            }
12333            res.priority = info.getPriority();
12334            res.preferredOrder = activity.owner.mPreferredOrder;
12335            //System.out.println("Result: " + res.activityInfo.className +
12336            //                   " = " + res.priority);
12337            res.match = match;
12338            res.isDefault = info.hasDefault;
12339            res.labelRes = info.labelRes;
12340            res.nonLocalizedLabel = info.nonLocalizedLabel;
12341            if (userNeedsBadging(userId)) {
12342                res.noResourceId = true;
12343            } else {
12344                res.icon = info.icon;
12345            }
12346            res.iconResourceId = info.icon;
12347            res.system = res.activityInfo.applicationInfo.isSystemApp();
12348            res.instantAppAvailable = userState.instantApp;
12349            return res;
12350        }
12351
12352        @Override
12353        protected void sortResults(List<ResolveInfo> results) {
12354            Collections.sort(results, mResolvePrioritySorter);
12355        }
12356
12357        @Override
12358        protected void dumpFilter(PrintWriter out, String prefix,
12359                PackageParser.ActivityIntentInfo filter) {
12360            out.print(prefix); out.print(
12361                    Integer.toHexString(System.identityHashCode(filter.activity)));
12362                    out.print(' ');
12363                    filter.activity.printComponentShortName(out);
12364                    out.print(" filter ");
12365                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12366        }
12367
12368        @Override
12369        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12370            return filter.activity;
12371        }
12372
12373        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12374            PackageParser.Activity activity = (PackageParser.Activity)label;
12375            out.print(prefix); out.print(
12376                    Integer.toHexString(System.identityHashCode(activity)));
12377                    out.print(' ');
12378                    activity.printComponentShortName(out);
12379            if (count > 1) {
12380                out.print(" ("); out.print(count); out.print(" filters)");
12381            }
12382            out.println();
12383        }
12384
12385        // Keys are String (activity class name), values are Activity.
12386        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12387                = new ArrayMap<ComponentName, PackageParser.Activity>();
12388        private int mFlags;
12389    }
12390
12391    private final class ServiceIntentResolver
12392            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12393        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12394                boolean defaultOnly, int userId) {
12395            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12396            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12397        }
12398
12399        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12400                int userId) {
12401            if (!sUserManager.exists(userId)) return null;
12402            mFlags = flags;
12403            return super.queryIntent(intent, resolvedType,
12404                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12405                    userId);
12406        }
12407
12408        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12409                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12410            if (!sUserManager.exists(userId)) return null;
12411            if (packageServices == null) {
12412                return null;
12413            }
12414            mFlags = flags;
12415            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12416            final int N = packageServices.size();
12417            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12418                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12419
12420            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12421            for (int i = 0; i < N; ++i) {
12422                intentFilters = packageServices.get(i).intents;
12423                if (intentFilters != null && intentFilters.size() > 0) {
12424                    PackageParser.ServiceIntentInfo[] array =
12425                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12426                    intentFilters.toArray(array);
12427                    listCut.add(array);
12428                }
12429            }
12430            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12431        }
12432
12433        public final void addService(PackageParser.Service s) {
12434            mServices.put(s.getComponentName(), s);
12435            if (DEBUG_SHOW_INFO) {
12436                Log.v(TAG, "  "
12437                        + (s.info.nonLocalizedLabel != null
12438                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12439                Log.v(TAG, "    Class=" + s.info.name);
12440            }
12441            final int NI = s.intents.size();
12442            int j;
12443            for (j=0; j<NI; j++) {
12444                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12445                if (DEBUG_SHOW_INFO) {
12446                    Log.v(TAG, "    IntentFilter:");
12447                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12448                }
12449                if (!intent.debugCheck()) {
12450                    Log.w(TAG, "==> For Service " + s.info.name);
12451                }
12452                addFilter(intent);
12453            }
12454        }
12455
12456        public final void removeService(PackageParser.Service s) {
12457            mServices.remove(s.getComponentName());
12458            if (DEBUG_SHOW_INFO) {
12459                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12460                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12461                Log.v(TAG, "    Class=" + s.info.name);
12462            }
12463            final int NI = s.intents.size();
12464            int j;
12465            for (j=0; j<NI; j++) {
12466                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12467                if (DEBUG_SHOW_INFO) {
12468                    Log.v(TAG, "    IntentFilter:");
12469                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12470                }
12471                removeFilter(intent);
12472            }
12473        }
12474
12475        @Override
12476        protected boolean allowFilterResult(
12477                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12478            ServiceInfo filterSi = filter.service.info;
12479            for (int i=dest.size()-1; i>=0; i--) {
12480                ServiceInfo destAi = dest.get(i).serviceInfo;
12481                if (destAi.name == filterSi.name
12482                        && destAi.packageName == filterSi.packageName) {
12483                    return false;
12484                }
12485            }
12486            return true;
12487        }
12488
12489        @Override
12490        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12491            return new PackageParser.ServiceIntentInfo[size];
12492        }
12493
12494        @Override
12495        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12496            if (!sUserManager.exists(userId)) return true;
12497            PackageParser.Package p = filter.service.owner;
12498            if (p != null) {
12499                PackageSetting ps = (PackageSetting)p.mExtras;
12500                if (ps != null) {
12501                    // System apps are never considered stopped for purposes of
12502                    // filtering, because there may be no way for the user to
12503                    // actually re-launch them.
12504                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12505                            && ps.getStopped(userId);
12506                }
12507            }
12508            return false;
12509        }
12510
12511        @Override
12512        protected boolean isPackageForFilter(String packageName,
12513                PackageParser.ServiceIntentInfo info) {
12514            return packageName.equals(info.service.owner.packageName);
12515        }
12516
12517        @Override
12518        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12519                int match, int userId) {
12520            if (!sUserManager.exists(userId)) return null;
12521            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12522            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12523                return null;
12524            }
12525            final PackageParser.Service service = info.service;
12526            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12527            if (ps == null) {
12528                return null;
12529            }
12530            final PackageUserState userState = ps.readUserState(userId);
12531            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12532                    userState, userId);
12533            if (si == null) {
12534                return null;
12535            }
12536            final boolean matchVisibleToInstantApp =
12537                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12538            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12539            // throw out filters that aren't visible to ephemeral apps
12540            if (matchVisibleToInstantApp
12541                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12542                return null;
12543            }
12544            // throw out ephemeral filters if we're not explicitly requesting them
12545            if (!isInstantApp && userState.instantApp) {
12546                return null;
12547            }
12548            // throw out instant app filters if updates are available; will trigger
12549            // instant app resolution
12550            if (userState.instantApp && ps.isUpdateAvailable()) {
12551                return null;
12552            }
12553            final ResolveInfo res = new ResolveInfo();
12554            res.serviceInfo = si;
12555            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12556                res.filter = filter;
12557            }
12558            res.priority = info.getPriority();
12559            res.preferredOrder = service.owner.mPreferredOrder;
12560            res.match = match;
12561            res.isDefault = info.hasDefault;
12562            res.labelRes = info.labelRes;
12563            res.nonLocalizedLabel = info.nonLocalizedLabel;
12564            res.icon = info.icon;
12565            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12566            return res;
12567        }
12568
12569        @Override
12570        protected void sortResults(List<ResolveInfo> results) {
12571            Collections.sort(results, mResolvePrioritySorter);
12572        }
12573
12574        @Override
12575        protected void dumpFilter(PrintWriter out, String prefix,
12576                PackageParser.ServiceIntentInfo filter) {
12577            out.print(prefix); out.print(
12578                    Integer.toHexString(System.identityHashCode(filter.service)));
12579                    out.print(' ');
12580                    filter.service.printComponentShortName(out);
12581                    out.print(" filter ");
12582                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12583        }
12584
12585        @Override
12586        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12587            return filter.service;
12588        }
12589
12590        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12591            PackageParser.Service service = (PackageParser.Service)label;
12592            out.print(prefix); out.print(
12593                    Integer.toHexString(System.identityHashCode(service)));
12594                    out.print(' ');
12595                    service.printComponentShortName(out);
12596            if (count > 1) {
12597                out.print(" ("); out.print(count); out.print(" filters)");
12598            }
12599            out.println();
12600        }
12601
12602//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12603//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12604//            final List<ResolveInfo> retList = Lists.newArrayList();
12605//            while (i.hasNext()) {
12606//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12607//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12608//                    retList.add(resolveInfo);
12609//                }
12610//            }
12611//            return retList;
12612//        }
12613
12614        // Keys are String (activity class name), values are Activity.
12615        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12616                = new ArrayMap<ComponentName, PackageParser.Service>();
12617        private int mFlags;
12618    }
12619
12620    private final class ProviderIntentResolver
12621            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12622        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12623                boolean defaultOnly, int userId) {
12624            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12625            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12626        }
12627
12628        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12629                int userId) {
12630            if (!sUserManager.exists(userId))
12631                return null;
12632            mFlags = flags;
12633            return super.queryIntent(intent, resolvedType,
12634                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12635                    userId);
12636        }
12637
12638        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12639                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12640            if (!sUserManager.exists(userId))
12641                return null;
12642            if (packageProviders == null) {
12643                return null;
12644            }
12645            mFlags = flags;
12646            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12647            final int N = packageProviders.size();
12648            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12649                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12650
12651            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12652            for (int i = 0; i < N; ++i) {
12653                intentFilters = packageProviders.get(i).intents;
12654                if (intentFilters != null && intentFilters.size() > 0) {
12655                    PackageParser.ProviderIntentInfo[] array =
12656                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12657                    intentFilters.toArray(array);
12658                    listCut.add(array);
12659                }
12660            }
12661            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12662        }
12663
12664        public final void addProvider(PackageParser.Provider p) {
12665            if (mProviders.containsKey(p.getComponentName())) {
12666                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12667                return;
12668            }
12669
12670            mProviders.put(p.getComponentName(), p);
12671            if (DEBUG_SHOW_INFO) {
12672                Log.v(TAG, "  "
12673                        + (p.info.nonLocalizedLabel != null
12674                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12675                Log.v(TAG, "    Class=" + p.info.name);
12676            }
12677            final int NI = p.intents.size();
12678            int j;
12679            for (j = 0; j < NI; j++) {
12680                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12681                if (DEBUG_SHOW_INFO) {
12682                    Log.v(TAG, "    IntentFilter:");
12683                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12684                }
12685                if (!intent.debugCheck()) {
12686                    Log.w(TAG, "==> For Provider " + p.info.name);
12687                }
12688                addFilter(intent);
12689            }
12690        }
12691
12692        public final void removeProvider(PackageParser.Provider p) {
12693            mProviders.remove(p.getComponentName());
12694            if (DEBUG_SHOW_INFO) {
12695                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12696                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12697                Log.v(TAG, "    Class=" + p.info.name);
12698            }
12699            final int NI = p.intents.size();
12700            int j;
12701            for (j = 0; j < NI; j++) {
12702                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12703                if (DEBUG_SHOW_INFO) {
12704                    Log.v(TAG, "    IntentFilter:");
12705                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12706                }
12707                removeFilter(intent);
12708            }
12709        }
12710
12711        @Override
12712        protected boolean allowFilterResult(
12713                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12714            ProviderInfo filterPi = filter.provider.info;
12715            for (int i = dest.size() - 1; i >= 0; i--) {
12716                ProviderInfo destPi = dest.get(i).providerInfo;
12717                if (destPi.name == filterPi.name
12718                        && destPi.packageName == filterPi.packageName) {
12719                    return false;
12720                }
12721            }
12722            return true;
12723        }
12724
12725        @Override
12726        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12727            return new PackageParser.ProviderIntentInfo[size];
12728        }
12729
12730        @Override
12731        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12732            if (!sUserManager.exists(userId))
12733                return true;
12734            PackageParser.Package p = filter.provider.owner;
12735            if (p != null) {
12736                PackageSetting ps = (PackageSetting) p.mExtras;
12737                if (ps != null) {
12738                    // System apps are never considered stopped for purposes of
12739                    // filtering, because there may be no way for the user to
12740                    // actually re-launch them.
12741                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12742                            && ps.getStopped(userId);
12743                }
12744            }
12745            return false;
12746        }
12747
12748        @Override
12749        protected boolean isPackageForFilter(String packageName,
12750                PackageParser.ProviderIntentInfo info) {
12751            return packageName.equals(info.provider.owner.packageName);
12752        }
12753
12754        @Override
12755        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12756                int match, int userId) {
12757            if (!sUserManager.exists(userId))
12758                return null;
12759            final PackageParser.ProviderIntentInfo info = filter;
12760            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12761                return null;
12762            }
12763            final PackageParser.Provider provider = info.provider;
12764            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12765            if (ps == null) {
12766                return null;
12767            }
12768            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12769                    ps.readUserState(userId), userId);
12770            if (pi == null) {
12771                return null;
12772            }
12773            final ResolveInfo res = new ResolveInfo();
12774            res.providerInfo = pi;
12775            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12776                res.filter = filter;
12777            }
12778            res.priority = info.getPriority();
12779            res.preferredOrder = provider.owner.mPreferredOrder;
12780            res.match = match;
12781            res.isDefault = info.hasDefault;
12782            res.labelRes = info.labelRes;
12783            res.nonLocalizedLabel = info.nonLocalizedLabel;
12784            res.icon = info.icon;
12785            res.system = res.providerInfo.applicationInfo.isSystemApp();
12786            return res;
12787        }
12788
12789        @Override
12790        protected void sortResults(List<ResolveInfo> results) {
12791            Collections.sort(results, mResolvePrioritySorter);
12792        }
12793
12794        @Override
12795        protected void dumpFilter(PrintWriter out, String prefix,
12796                PackageParser.ProviderIntentInfo filter) {
12797            out.print(prefix);
12798            out.print(
12799                    Integer.toHexString(System.identityHashCode(filter.provider)));
12800            out.print(' ');
12801            filter.provider.printComponentShortName(out);
12802            out.print(" filter ");
12803            out.println(Integer.toHexString(System.identityHashCode(filter)));
12804        }
12805
12806        @Override
12807        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12808            return filter.provider;
12809        }
12810
12811        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12812            PackageParser.Provider provider = (PackageParser.Provider)label;
12813            out.print(prefix); out.print(
12814                    Integer.toHexString(System.identityHashCode(provider)));
12815                    out.print(' ');
12816                    provider.printComponentShortName(out);
12817            if (count > 1) {
12818                out.print(" ("); out.print(count); out.print(" filters)");
12819            }
12820            out.println();
12821        }
12822
12823        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12824                = new ArrayMap<ComponentName, PackageParser.Provider>();
12825        private int mFlags;
12826    }
12827
12828    static final class EphemeralIntentResolver
12829            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12830        /**
12831         * The result that has the highest defined order. Ordering applies on a
12832         * per-package basis. Mapping is from package name to Pair of order and
12833         * EphemeralResolveInfo.
12834         * <p>
12835         * NOTE: This is implemented as a field variable for convenience and efficiency.
12836         * By having a field variable, we're able to track filter ordering as soon as
12837         * a non-zero order is defined. Otherwise, multiple loops across the result set
12838         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12839         * this needs to be contained entirely within {@link #filterResults}.
12840         */
12841        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12842
12843        @Override
12844        protected AuxiliaryResolveInfo[] newArray(int size) {
12845            return new AuxiliaryResolveInfo[size];
12846        }
12847
12848        @Override
12849        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12850            return true;
12851        }
12852
12853        @Override
12854        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12855                int userId) {
12856            if (!sUserManager.exists(userId)) {
12857                return null;
12858            }
12859            final String packageName = responseObj.resolveInfo.getPackageName();
12860            final Integer order = responseObj.getOrder();
12861            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12862                    mOrderResult.get(packageName);
12863            // ordering is enabled and this item's order isn't high enough
12864            if (lastOrderResult != null && lastOrderResult.first >= order) {
12865                return null;
12866            }
12867            final InstantAppResolveInfo res = responseObj.resolveInfo;
12868            if (order > 0) {
12869                // non-zero order, enable ordering
12870                mOrderResult.put(packageName, new Pair<>(order, res));
12871            }
12872            return responseObj;
12873        }
12874
12875        @Override
12876        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12877            // only do work if ordering is enabled [most of the time it won't be]
12878            if (mOrderResult.size() == 0) {
12879                return;
12880            }
12881            int resultSize = results.size();
12882            for (int i = 0; i < resultSize; i++) {
12883                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12884                final String packageName = info.getPackageName();
12885                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12886                if (savedInfo == null) {
12887                    // package doesn't having ordering
12888                    continue;
12889                }
12890                if (savedInfo.second == info) {
12891                    // circled back to the highest ordered item; remove from order list
12892                    mOrderResult.remove(savedInfo);
12893                    if (mOrderResult.size() == 0) {
12894                        // no more ordered items
12895                        break;
12896                    }
12897                    continue;
12898                }
12899                // item has a worse order, remove it from the result list
12900                results.remove(i);
12901                resultSize--;
12902                i--;
12903            }
12904        }
12905    }
12906
12907    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12908            new Comparator<ResolveInfo>() {
12909        public int compare(ResolveInfo r1, ResolveInfo r2) {
12910            int v1 = r1.priority;
12911            int v2 = r2.priority;
12912            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12913            if (v1 != v2) {
12914                return (v1 > v2) ? -1 : 1;
12915            }
12916            v1 = r1.preferredOrder;
12917            v2 = r2.preferredOrder;
12918            if (v1 != v2) {
12919                return (v1 > v2) ? -1 : 1;
12920            }
12921            if (r1.isDefault != r2.isDefault) {
12922                return r1.isDefault ? -1 : 1;
12923            }
12924            v1 = r1.match;
12925            v2 = r2.match;
12926            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12927            if (v1 != v2) {
12928                return (v1 > v2) ? -1 : 1;
12929            }
12930            if (r1.system != r2.system) {
12931                return r1.system ? -1 : 1;
12932            }
12933            if (r1.activityInfo != null) {
12934                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12935            }
12936            if (r1.serviceInfo != null) {
12937                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12938            }
12939            if (r1.providerInfo != null) {
12940                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12941            }
12942            return 0;
12943        }
12944    };
12945
12946    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12947            new Comparator<ProviderInfo>() {
12948        public int compare(ProviderInfo p1, ProviderInfo p2) {
12949            final int v1 = p1.initOrder;
12950            final int v2 = p2.initOrder;
12951            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12952        }
12953    };
12954
12955    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12956            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12957            final int[] userIds) {
12958        mHandler.post(new Runnable() {
12959            @Override
12960            public void run() {
12961                try {
12962                    final IActivityManager am = ActivityManager.getService();
12963                    if (am == null) return;
12964                    final int[] resolvedUserIds;
12965                    if (userIds == null) {
12966                        resolvedUserIds = am.getRunningUserIds();
12967                    } else {
12968                        resolvedUserIds = userIds;
12969                    }
12970                    for (int id : resolvedUserIds) {
12971                        final Intent intent = new Intent(action,
12972                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12973                        if (extras != null) {
12974                            intent.putExtras(extras);
12975                        }
12976                        if (targetPkg != null) {
12977                            intent.setPackage(targetPkg);
12978                        }
12979                        // Modify the UID when posting to other users
12980                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12981                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12982                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12983                            intent.putExtra(Intent.EXTRA_UID, uid);
12984                        }
12985                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12986                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12987                        if (DEBUG_BROADCASTS) {
12988                            RuntimeException here = new RuntimeException("here");
12989                            here.fillInStackTrace();
12990                            Slog.d(TAG, "Sending to user " + id + ": "
12991                                    + intent.toShortString(false, true, false, false)
12992                                    + " " + intent.getExtras(), here);
12993                        }
12994                        am.broadcastIntent(null, intent, null, finishedReceiver,
12995                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12996                                null, finishedReceiver != null, false, id);
12997                    }
12998                } catch (RemoteException ex) {
12999                }
13000            }
13001        });
13002    }
13003
13004    /**
13005     * Check if the external storage media is available. This is true if there
13006     * is a mounted external storage medium or if the external storage is
13007     * emulated.
13008     */
13009    private boolean isExternalMediaAvailable() {
13010        return mMediaMounted || Environment.isExternalStorageEmulated();
13011    }
13012
13013    @Override
13014    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13015        // writer
13016        synchronized (mPackages) {
13017            if (!isExternalMediaAvailable()) {
13018                // If the external storage is no longer mounted at this point,
13019                // the caller may not have been able to delete all of this
13020                // packages files and can not delete any more.  Bail.
13021                return null;
13022            }
13023            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13024            if (lastPackage != null) {
13025                pkgs.remove(lastPackage);
13026            }
13027            if (pkgs.size() > 0) {
13028                return pkgs.get(0);
13029            }
13030        }
13031        return null;
13032    }
13033
13034    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13035        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13036                userId, andCode ? 1 : 0, packageName);
13037        if (mSystemReady) {
13038            msg.sendToTarget();
13039        } else {
13040            if (mPostSystemReadyMessages == null) {
13041                mPostSystemReadyMessages = new ArrayList<>();
13042            }
13043            mPostSystemReadyMessages.add(msg);
13044        }
13045    }
13046
13047    void startCleaningPackages() {
13048        // reader
13049        if (!isExternalMediaAvailable()) {
13050            return;
13051        }
13052        synchronized (mPackages) {
13053            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13054                return;
13055            }
13056        }
13057        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13058        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13059        IActivityManager am = ActivityManager.getService();
13060        if (am != null) {
13061            int dcsUid = -1;
13062            synchronized (mPackages) {
13063                if (!mDefaultContainerWhitelisted) {
13064                    mDefaultContainerWhitelisted = true;
13065                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13066                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13067                }
13068            }
13069            try {
13070                if (dcsUid > 0) {
13071                    am.backgroundWhitelistUid(dcsUid);
13072                }
13073                am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(),
13074                        UserHandle.USER_SYSTEM);
13075            } catch (RemoteException e) {
13076            }
13077        }
13078    }
13079
13080    @Override
13081    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13082            int installFlags, String installerPackageName, int userId) {
13083        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13084
13085        final int callingUid = Binder.getCallingUid();
13086        enforceCrossUserPermission(callingUid, userId,
13087                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13088
13089        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13090            try {
13091                if (observer != null) {
13092                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13093                }
13094            } catch (RemoteException re) {
13095            }
13096            return;
13097        }
13098
13099        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13100            installFlags |= PackageManager.INSTALL_FROM_ADB;
13101
13102        } else {
13103            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13104            // about installerPackageName.
13105
13106            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13107            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13108        }
13109
13110        UserHandle user;
13111        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13112            user = UserHandle.ALL;
13113        } else {
13114            user = new UserHandle(userId);
13115        }
13116
13117        // Only system components can circumvent runtime permissions when installing.
13118        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13119                && mContext.checkCallingOrSelfPermission(Manifest.permission
13120                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13121            throw new SecurityException("You need the "
13122                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13123                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13124        }
13125
13126        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13127                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13128            throw new IllegalArgumentException(
13129                    "New installs into ASEC containers no longer supported");
13130        }
13131
13132        final File originFile = new File(originPath);
13133        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13134
13135        final Message msg = mHandler.obtainMessage(INIT_COPY);
13136        final VerificationInfo verificationInfo = new VerificationInfo(
13137                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13138        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13139                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13140                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13141                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13142        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13143        msg.obj = params;
13144
13145        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13146                System.identityHashCode(msg.obj));
13147        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13148                System.identityHashCode(msg.obj));
13149
13150        mHandler.sendMessage(msg);
13151    }
13152
13153
13154    /**
13155     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13156     * it is acting on behalf on an enterprise or the user).
13157     *
13158     * Note that the ordering of the conditionals in this method is important. The checks we perform
13159     * are as follows, in this order:
13160     *
13161     * 1) If the install is being performed by a system app, we can trust the app to have set the
13162     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13163     *    what it is.
13164     * 2) If the install is being performed by a device or profile owner app, the install reason
13165     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13166     *    set the install reason correctly. If the app targets an older SDK version where install
13167     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13168     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13169     * 3) In all other cases, the install is being performed by a regular app that is neither part
13170     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13171     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13172     *    set to enterprise policy and if so, change it to unknown instead.
13173     */
13174    private int fixUpInstallReason(String installerPackageName, int installerUid,
13175            int installReason) {
13176        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13177                == PERMISSION_GRANTED) {
13178            // If the install is being performed by a system app, we trust that app to have set the
13179            // install reason correctly.
13180            return installReason;
13181        }
13182
13183        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13184            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13185        if (dpm != null) {
13186            ComponentName owner = null;
13187            try {
13188                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13189                if (owner == null) {
13190                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13191                }
13192            } catch (RemoteException e) {
13193            }
13194            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13195                // If the install is being performed by a device or profile owner, the install
13196                // reason should be enterprise policy.
13197                return PackageManager.INSTALL_REASON_POLICY;
13198            }
13199        }
13200
13201        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13202            // If the install is being performed by a regular app (i.e. neither system app nor
13203            // device or profile owner), we have no reason to believe that the app is acting on
13204            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13205            // change it to unknown instead.
13206            return PackageManager.INSTALL_REASON_UNKNOWN;
13207        }
13208
13209        // If the install is being performed by a regular app and the install reason was set to any
13210        // value but enterprise policy, leave the install reason unchanged.
13211        return installReason;
13212    }
13213
13214    void installStage(String packageName, File stagedDir, String stagedCid,
13215            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13216            String installerPackageName, int installerUid, UserHandle user,
13217            Certificate[][] certificates) {
13218        if (DEBUG_EPHEMERAL) {
13219            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13220                Slog.d(TAG, "Ephemeral install of " + packageName);
13221            }
13222        }
13223        final VerificationInfo verificationInfo = new VerificationInfo(
13224                sessionParams.originatingUri, sessionParams.referrerUri,
13225                sessionParams.originatingUid, installerUid);
13226
13227        final OriginInfo origin;
13228        if (stagedDir != null) {
13229            origin = OriginInfo.fromStagedFile(stagedDir);
13230        } else {
13231            origin = OriginInfo.fromStagedContainer(stagedCid);
13232        }
13233
13234        final Message msg = mHandler.obtainMessage(INIT_COPY);
13235        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13236                sessionParams.installReason);
13237        final InstallParams params = new InstallParams(origin, null, observer,
13238                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13239                verificationInfo, user, sessionParams.abiOverride,
13240                sessionParams.grantedRuntimePermissions, certificates, installReason);
13241        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13242        msg.obj = params;
13243
13244        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13245                System.identityHashCode(msg.obj));
13246        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13247                System.identityHashCode(msg.obj));
13248
13249        mHandler.sendMessage(msg);
13250    }
13251
13252    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13253            int userId) {
13254        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13255        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13256    }
13257
13258    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13259            int appId, int... userIds) {
13260        if (ArrayUtils.isEmpty(userIds)) {
13261            return;
13262        }
13263        Bundle extras = new Bundle(1);
13264        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13265        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13266
13267        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13268                packageName, extras, 0, null, null, userIds);
13269        if (isSystem) {
13270            mHandler.post(() -> {
13271                        for (int userId : userIds) {
13272                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13273                        }
13274                    }
13275            );
13276        }
13277    }
13278
13279    /**
13280     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13281     * automatically without needing an explicit launch.
13282     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13283     */
13284    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13285        // If user is not running, the app didn't miss any broadcast
13286        if (!mUserManagerInternal.isUserRunning(userId)) {
13287            return;
13288        }
13289        final IActivityManager am = ActivityManager.getService();
13290        try {
13291            // Deliver LOCKED_BOOT_COMPLETED first
13292            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13293                    .setPackage(packageName);
13294            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13295            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13296                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13297
13298            // Deliver BOOT_COMPLETED only if user is unlocked
13299            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13300                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13301                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13302                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13303            }
13304        } catch (RemoteException e) {
13305            throw e.rethrowFromSystemServer();
13306        }
13307    }
13308
13309    @Override
13310    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13311            int userId) {
13312        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13313        PackageSetting pkgSetting;
13314        final int uid = Binder.getCallingUid();
13315        enforceCrossUserPermission(uid, userId,
13316                true /* requireFullPermission */, true /* checkShell */,
13317                "setApplicationHiddenSetting for user " + userId);
13318
13319        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13320            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13321            return false;
13322        }
13323
13324        long callingId = Binder.clearCallingIdentity();
13325        try {
13326            boolean sendAdded = false;
13327            boolean sendRemoved = false;
13328            // writer
13329            synchronized (mPackages) {
13330                pkgSetting = mSettings.mPackages.get(packageName);
13331                if (pkgSetting == null) {
13332                    return false;
13333                }
13334                // Do not allow "android" is being disabled
13335                if ("android".equals(packageName)) {
13336                    Slog.w(TAG, "Cannot hide package: android");
13337                    return false;
13338                }
13339                // Cannot hide static shared libs as they are considered
13340                // a part of the using app (emulating static linking). Also
13341                // static libs are installed always on internal storage.
13342                PackageParser.Package pkg = mPackages.get(packageName);
13343                if (pkg != null && pkg.staticSharedLibName != null) {
13344                    Slog.w(TAG, "Cannot hide package: " + packageName
13345                            + " providing static shared library: "
13346                            + pkg.staticSharedLibName);
13347                    return false;
13348                }
13349                // Only allow protected packages to hide themselves.
13350                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13351                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13352                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13353                    return false;
13354                }
13355
13356                if (pkgSetting.getHidden(userId) != hidden) {
13357                    pkgSetting.setHidden(hidden, userId);
13358                    mSettings.writePackageRestrictionsLPr(userId);
13359                    if (hidden) {
13360                        sendRemoved = true;
13361                    } else {
13362                        sendAdded = true;
13363                    }
13364                }
13365            }
13366            if (sendAdded) {
13367                sendPackageAddedForUser(packageName, pkgSetting, userId);
13368                return true;
13369            }
13370            if (sendRemoved) {
13371                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13372                        "hiding pkg");
13373                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13374                return true;
13375            }
13376        } finally {
13377            Binder.restoreCallingIdentity(callingId);
13378        }
13379        return false;
13380    }
13381
13382    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13383            int userId) {
13384        final PackageRemovedInfo info = new PackageRemovedInfo();
13385        info.removedPackage = packageName;
13386        info.removedUsers = new int[] {userId};
13387        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13388        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13389    }
13390
13391    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13392        if (pkgList.length > 0) {
13393            Bundle extras = new Bundle(1);
13394            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13395
13396            sendPackageBroadcast(
13397                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13398                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13399                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13400                    new int[] {userId});
13401        }
13402    }
13403
13404    /**
13405     * Returns true if application is not found or there was an error. Otherwise it returns
13406     * the hidden state of the package for the given user.
13407     */
13408    @Override
13409    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13410        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13412                true /* requireFullPermission */, false /* checkShell */,
13413                "getApplicationHidden for user " + userId);
13414        PackageSetting pkgSetting;
13415        long callingId = Binder.clearCallingIdentity();
13416        try {
13417            // writer
13418            synchronized (mPackages) {
13419                pkgSetting = mSettings.mPackages.get(packageName);
13420                if (pkgSetting == null) {
13421                    return true;
13422                }
13423                return pkgSetting.getHidden(userId);
13424            }
13425        } finally {
13426            Binder.restoreCallingIdentity(callingId);
13427        }
13428    }
13429
13430    /**
13431     * @hide
13432     */
13433    @Override
13434    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13435            int installReason) {
13436        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13437                null);
13438        PackageSetting pkgSetting;
13439        final int uid = Binder.getCallingUid();
13440        enforceCrossUserPermission(uid, userId,
13441                true /* requireFullPermission */, true /* checkShell */,
13442                "installExistingPackage for user " + userId);
13443        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13444            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13445        }
13446
13447        long callingId = Binder.clearCallingIdentity();
13448        try {
13449            boolean installed = false;
13450            final boolean instantApp =
13451                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13452            final boolean fullApp =
13453                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13454
13455            // writer
13456            synchronized (mPackages) {
13457                pkgSetting = mSettings.mPackages.get(packageName);
13458                if (pkgSetting == null) {
13459                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13460                }
13461                if (!pkgSetting.getInstalled(userId)) {
13462                    pkgSetting.setInstalled(true, userId);
13463                    pkgSetting.setHidden(false, userId);
13464                    pkgSetting.setInstallReason(installReason, userId);
13465                    mSettings.writePackageRestrictionsLPr(userId);
13466                    mSettings.writeKernelMappingLPr(pkgSetting);
13467                    installed = true;
13468                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13469                    // upgrade app from instant to full; we don't allow app downgrade
13470                    installed = true;
13471                }
13472                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13473            }
13474
13475            if (installed) {
13476                if (pkgSetting.pkg != null) {
13477                    synchronized (mInstallLock) {
13478                        // We don't need to freeze for a brand new install
13479                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13480                    }
13481                }
13482                sendPackageAddedForUser(packageName, pkgSetting, userId);
13483                synchronized (mPackages) {
13484                    updateSequenceNumberLP(packageName, new int[]{ userId });
13485                }
13486            }
13487        } finally {
13488            Binder.restoreCallingIdentity(callingId);
13489        }
13490
13491        return PackageManager.INSTALL_SUCCEEDED;
13492    }
13493
13494    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13495            boolean instantApp, boolean fullApp) {
13496        // no state specified; do nothing
13497        if (!instantApp && !fullApp) {
13498            return;
13499        }
13500        if (userId != UserHandle.USER_ALL) {
13501            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13502                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13503            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13504                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13505            }
13506        } else {
13507            for (int currentUserId : sUserManager.getUserIds()) {
13508                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13509                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13510                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13511                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13512                }
13513            }
13514        }
13515    }
13516
13517    boolean isUserRestricted(int userId, String restrictionKey) {
13518        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13519        if (restrictions.getBoolean(restrictionKey, false)) {
13520            Log.w(TAG, "User is restricted: " + restrictionKey);
13521            return true;
13522        }
13523        return false;
13524    }
13525
13526    @Override
13527    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13528            int userId) {
13529        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13530        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13531                true /* requireFullPermission */, true /* checkShell */,
13532                "setPackagesSuspended for user " + userId);
13533
13534        if (ArrayUtils.isEmpty(packageNames)) {
13535            return packageNames;
13536        }
13537
13538        // List of package names for whom the suspended state has changed.
13539        List<String> changedPackages = new ArrayList<>(packageNames.length);
13540        // List of package names for whom the suspended state is not set as requested in this
13541        // method.
13542        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13543        long callingId = Binder.clearCallingIdentity();
13544        try {
13545            for (int i = 0; i < packageNames.length; i++) {
13546                String packageName = packageNames[i];
13547                boolean changed = false;
13548                final int appId;
13549                synchronized (mPackages) {
13550                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13551                    if (pkgSetting == null) {
13552                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13553                                + "\". Skipping suspending/un-suspending.");
13554                        unactionedPackages.add(packageName);
13555                        continue;
13556                    }
13557                    appId = pkgSetting.appId;
13558                    if (pkgSetting.getSuspended(userId) != suspended) {
13559                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13560                            unactionedPackages.add(packageName);
13561                            continue;
13562                        }
13563                        pkgSetting.setSuspended(suspended, userId);
13564                        mSettings.writePackageRestrictionsLPr(userId);
13565                        changed = true;
13566                        changedPackages.add(packageName);
13567                    }
13568                }
13569
13570                if (changed && suspended) {
13571                    killApplication(packageName, UserHandle.getUid(userId, appId),
13572                            "suspending package");
13573                }
13574            }
13575        } finally {
13576            Binder.restoreCallingIdentity(callingId);
13577        }
13578
13579        if (!changedPackages.isEmpty()) {
13580            sendPackagesSuspendedForUser(changedPackages.toArray(
13581                    new String[changedPackages.size()]), userId, suspended);
13582        }
13583
13584        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13585    }
13586
13587    @Override
13588    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13589        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13590                true /* requireFullPermission */, false /* checkShell */,
13591                "isPackageSuspendedForUser for user " + userId);
13592        synchronized (mPackages) {
13593            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13594            if (pkgSetting == null) {
13595                throw new IllegalArgumentException("Unknown target package: " + packageName);
13596            }
13597            return pkgSetting.getSuspended(userId);
13598        }
13599    }
13600
13601    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13602        if (isPackageDeviceAdmin(packageName, userId)) {
13603            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13604                    + "\": has an active device admin");
13605            return false;
13606        }
13607
13608        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13609        if (packageName.equals(activeLauncherPackageName)) {
13610            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13611                    + "\": contains the active launcher");
13612            return false;
13613        }
13614
13615        if (packageName.equals(mRequiredInstallerPackage)) {
13616            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13617                    + "\": required for package installation");
13618            return false;
13619        }
13620
13621        if (packageName.equals(mRequiredUninstallerPackage)) {
13622            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13623                    + "\": required for package uninstallation");
13624            return false;
13625        }
13626
13627        if (packageName.equals(mRequiredVerifierPackage)) {
13628            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13629                    + "\": required for package verification");
13630            return false;
13631        }
13632
13633        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13634            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13635                    + "\": is the default dialer");
13636            return false;
13637        }
13638
13639        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13640            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13641                    + "\": protected package");
13642            return false;
13643        }
13644
13645        // Cannot suspend static shared libs as they are considered
13646        // a part of the using app (emulating static linking). Also
13647        // static libs are installed always on internal storage.
13648        PackageParser.Package pkg = mPackages.get(packageName);
13649        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13650            Slog.w(TAG, "Cannot suspend package: " + packageName
13651                    + " providing static shared library: "
13652                    + pkg.staticSharedLibName);
13653            return false;
13654        }
13655
13656        return true;
13657    }
13658
13659    private String getActiveLauncherPackageName(int userId) {
13660        Intent intent = new Intent(Intent.ACTION_MAIN);
13661        intent.addCategory(Intent.CATEGORY_HOME);
13662        ResolveInfo resolveInfo = resolveIntent(
13663                intent,
13664                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13665                PackageManager.MATCH_DEFAULT_ONLY,
13666                userId);
13667
13668        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13669    }
13670
13671    private String getDefaultDialerPackageName(int userId) {
13672        synchronized (mPackages) {
13673            return mSettings.getDefaultDialerPackageNameLPw(userId);
13674        }
13675    }
13676
13677    @Override
13678    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13679        mContext.enforceCallingOrSelfPermission(
13680                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13681                "Only package verification agents can verify applications");
13682
13683        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13684        final PackageVerificationResponse response = new PackageVerificationResponse(
13685                verificationCode, Binder.getCallingUid());
13686        msg.arg1 = id;
13687        msg.obj = response;
13688        mHandler.sendMessage(msg);
13689    }
13690
13691    @Override
13692    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13693            long millisecondsToDelay) {
13694        mContext.enforceCallingOrSelfPermission(
13695                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13696                "Only package verification agents can extend verification timeouts");
13697
13698        final PackageVerificationState state = mPendingVerification.get(id);
13699        final PackageVerificationResponse response = new PackageVerificationResponse(
13700                verificationCodeAtTimeout, Binder.getCallingUid());
13701
13702        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13703            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13704        }
13705        if (millisecondsToDelay < 0) {
13706            millisecondsToDelay = 0;
13707        }
13708        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13709                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13710            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13711        }
13712
13713        if ((state != null) && !state.timeoutExtended()) {
13714            state.extendTimeout();
13715
13716            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13717            msg.arg1 = id;
13718            msg.obj = response;
13719            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13720        }
13721    }
13722
13723    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13724            int verificationCode, UserHandle user) {
13725        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13726        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13727        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13728        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13729        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13730
13731        mContext.sendBroadcastAsUser(intent, user,
13732                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13733    }
13734
13735    private ComponentName matchComponentForVerifier(String packageName,
13736            List<ResolveInfo> receivers) {
13737        ActivityInfo targetReceiver = null;
13738
13739        final int NR = receivers.size();
13740        for (int i = 0; i < NR; i++) {
13741            final ResolveInfo info = receivers.get(i);
13742            if (info.activityInfo == null) {
13743                continue;
13744            }
13745
13746            if (packageName.equals(info.activityInfo.packageName)) {
13747                targetReceiver = info.activityInfo;
13748                break;
13749            }
13750        }
13751
13752        if (targetReceiver == null) {
13753            return null;
13754        }
13755
13756        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13757    }
13758
13759    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13760            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13761        if (pkgInfo.verifiers.length == 0) {
13762            return null;
13763        }
13764
13765        final int N = pkgInfo.verifiers.length;
13766        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13767        for (int i = 0; i < N; i++) {
13768            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13769
13770            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13771                    receivers);
13772            if (comp == null) {
13773                continue;
13774            }
13775
13776            final int verifierUid = getUidForVerifier(verifierInfo);
13777            if (verifierUid == -1) {
13778                continue;
13779            }
13780
13781            if (DEBUG_VERIFY) {
13782                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13783                        + " with the correct signature");
13784            }
13785            sufficientVerifiers.add(comp);
13786            verificationState.addSufficientVerifier(verifierUid);
13787        }
13788
13789        return sufficientVerifiers;
13790    }
13791
13792    private int getUidForVerifier(VerifierInfo verifierInfo) {
13793        synchronized (mPackages) {
13794            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13795            if (pkg == null) {
13796                return -1;
13797            } else if (pkg.mSignatures.length != 1) {
13798                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13799                        + " has more than one signature; ignoring");
13800                return -1;
13801            }
13802
13803            /*
13804             * If the public key of the package's signature does not match
13805             * our expected public key, then this is a different package and
13806             * we should skip.
13807             */
13808
13809            final byte[] expectedPublicKey;
13810            try {
13811                final Signature verifierSig = pkg.mSignatures[0];
13812                final PublicKey publicKey = verifierSig.getPublicKey();
13813                expectedPublicKey = publicKey.getEncoded();
13814            } catch (CertificateException e) {
13815                return -1;
13816            }
13817
13818            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13819
13820            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13821                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13822                        + " does not have the expected public key; ignoring");
13823                return -1;
13824            }
13825
13826            return pkg.applicationInfo.uid;
13827        }
13828    }
13829
13830    @Override
13831    public void finishPackageInstall(int token, boolean didLaunch) {
13832        enforceSystemOrRoot("Only the system is allowed to finish installs");
13833
13834        if (DEBUG_INSTALL) {
13835            Slog.v(TAG, "BM finishing package install for " + token);
13836        }
13837        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13838
13839        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13840        mHandler.sendMessage(msg);
13841    }
13842
13843    /**
13844     * Get the verification agent timeout.
13845     *
13846     * @return verification timeout in milliseconds
13847     */
13848    private long getVerificationTimeout() {
13849        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13850                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13851                DEFAULT_VERIFICATION_TIMEOUT);
13852    }
13853
13854    /**
13855     * Get the default verification agent response code.
13856     *
13857     * @return default verification response code
13858     */
13859    private int getDefaultVerificationResponse() {
13860        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13861                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13862                DEFAULT_VERIFICATION_RESPONSE);
13863    }
13864
13865    /**
13866     * Check whether or not package verification has been enabled.
13867     *
13868     * @return true if verification should be performed
13869     */
13870    private boolean isVerificationEnabled(int userId, int installFlags) {
13871        if (!DEFAULT_VERIFY_ENABLE) {
13872            return false;
13873        }
13874
13875        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13876
13877        // Check if installing from ADB
13878        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13879            // Do not run verification in a test harness environment
13880            if (ActivityManager.isRunningInTestHarness()) {
13881                return false;
13882            }
13883            if (ensureVerifyAppsEnabled) {
13884                return true;
13885            }
13886            // Check if the developer does not want package verification for ADB installs
13887            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13888                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13889                return false;
13890            }
13891        }
13892
13893        if (ensureVerifyAppsEnabled) {
13894            return true;
13895        }
13896
13897        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13898                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13899    }
13900
13901    @Override
13902    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13903            throws RemoteException {
13904        mContext.enforceCallingOrSelfPermission(
13905                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13906                "Only intentfilter verification agents can verify applications");
13907
13908        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13909        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13910                Binder.getCallingUid(), verificationCode, failedDomains);
13911        msg.arg1 = id;
13912        msg.obj = response;
13913        mHandler.sendMessage(msg);
13914    }
13915
13916    @Override
13917    public int getIntentVerificationStatus(String packageName, int userId) {
13918        synchronized (mPackages) {
13919            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13920        }
13921    }
13922
13923    @Override
13924    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13925        mContext.enforceCallingOrSelfPermission(
13926                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13927
13928        boolean result = false;
13929        synchronized (mPackages) {
13930            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13931        }
13932        if (result) {
13933            scheduleWritePackageRestrictionsLocked(userId);
13934        }
13935        return result;
13936    }
13937
13938    @Override
13939    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13940            String packageName) {
13941        synchronized (mPackages) {
13942            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13943        }
13944    }
13945
13946    @Override
13947    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13948        if (TextUtils.isEmpty(packageName)) {
13949            return ParceledListSlice.emptyList();
13950        }
13951        synchronized (mPackages) {
13952            PackageParser.Package pkg = mPackages.get(packageName);
13953            if (pkg == null || pkg.activities == null) {
13954                return ParceledListSlice.emptyList();
13955            }
13956            final int count = pkg.activities.size();
13957            ArrayList<IntentFilter> result = new ArrayList<>();
13958            for (int n=0; n<count; n++) {
13959                PackageParser.Activity activity = pkg.activities.get(n);
13960                if (activity.intents != null && activity.intents.size() > 0) {
13961                    result.addAll(activity.intents);
13962                }
13963            }
13964            return new ParceledListSlice<>(result);
13965        }
13966    }
13967
13968    @Override
13969    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13970        mContext.enforceCallingOrSelfPermission(
13971                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13972
13973        synchronized (mPackages) {
13974            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13975            if (packageName != null) {
13976                result |= updateIntentVerificationStatus(packageName,
13977                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13978                        userId);
13979                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13980                        packageName, userId);
13981            }
13982            return result;
13983        }
13984    }
13985
13986    @Override
13987    public String getDefaultBrowserPackageName(int userId) {
13988        synchronized (mPackages) {
13989            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13990        }
13991    }
13992
13993    /**
13994     * Get the "allow unknown sources" setting.
13995     *
13996     * @return the current "allow unknown sources" setting
13997     */
13998    private int getUnknownSourcesSettings() {
13999        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14000                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14001                -1);
14002    }
14003
14004    @Override
14005    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14006        final int uid = Binder.getCallingUid();
14007        // writer
14008        synchronized (mPackages) {
14009            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14010            if (targetPackageSetting == null) {
14011                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14012            }
14013
14014            PackageSetting installerPackageSetting;
14015            if (installerPackageName != null) {
14016                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14017                if (installerPackageSetting == null) {
14018                    throw new IllegalArgumentException("Unknown installer package: "
14019                            + installerPackageName);
14020                }
14021            } else {
14022                installerPackageSetting = null;
14023            }
14024
14025            Signature[] callerSignature;
14026            Object obj = mSettings.getUserIdLPr(uid);
14027            if (obj != null) {
14028                if (obj instanceof SharedUserSetting) {
14029                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14030                } else if (obj instanceof PackageSetting) {
14031                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14032                } else {
14033                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14034                }
14035            } else {
14036                throw new SecurityException("Unknown calling UID: " + uid);
14037            }
14038
14039            // Verify: can't set installerPackageName to a package that is
14040            // not signed with the same cert as the caller.
14041            if (installerPackageSetting != null) {
14042                if (compareSignatures(callerSignature,
14043                        installerPackageSetting.signatures.mSignatures)
14044                        != PackageManager.SIGNATURE_MATCH) {
14045                    throw new SecurityException(
14046                            "Caller does not have same cert as new installer package "
14047                            + installerPackageName);
14048                }
14049            }
14050
14051            // Verify: if target already has an installer package, it must
14052            // be signed with the same cert as the caller.
14053            if (targetPackageSetting.installerPackageName != null) {
14054                PackageSetting setting = mSettings.mPackages.get(
14055                        targetPackageSetting.installerPackageName);
14056                // If the currently set package isn't valid, then it's always
14057                // okay to change it.
14058                if (setting != null) {
14059                    if (compareSignatures(callerSignature,
14060                            setting.signatures.mSignatures)
14061                            != PackageManager.SIGNATURE_MATCH) {
14062                        throw new SecurityException(
14063                                "Caller does not have same cert as old installer package "
14064                                + targetPackageSetting.installerPackageName);
14065                    }
14066                }
14067            }
14068
14069            // Okay!
14070            targetPackageSetting.installerPackageName = installerPackageName;
14071            if (installerPackageName != null) {
14072                mSettings.mInstallerPackages.add(installerPackageName);
14073            }
14074            scheduleWriteSettingsLocked();
14075        }
14076    }
14077
14078    @Override
14079    public void setApplicationCategoryHint(String packageName, int categoryHint,
14080            String callerPackageName) {
14081        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14082                callerPackageName);
14083        synchronized (mPackages) {
14084            PackageSetting ps = mSettings.mPackages.get(packageName);
14085            if (ps == null) {
14086                throw new IllegalArgumentException("Unknown target package " + packageName);
14087            }
14088
14089            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14090                throw new IllegalArgumentException("Calling package " + callerPackageName
14091                        + " is not installer for " + packageName);
14092            }
14093
14094            if (ps.categoryHint != categoryHint) {
14095                ps.categoryHint = categoryHint;
14096                scheduleWriteSettingsLocked();
14097            }
14098        }
14099    }
14100
14101    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14102        // Queue up an async operation since the package installation may take a little while.
14103        mHandler.post(new Runnable() {
14104            public void run() {
14105                mHandler.removeCallbacks(this);
14106                 // Result object to be returned
14107                PackageInstalledInfo res = new PackageInstalledInfo();
14108                res.setReturnCode(currentStatus);
14109                res.uid = -1;
14110                res.pkg = null;
14111                res.removedInfo = null;
14112                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14113                    args.doPreInstall(res.returnCode);
14114                    synchronized (mInstallLock) {
14115                        installPackageTracedLI(args, res);
14116                    }
14117                    args.doPostInstall(res.returnCode, res.uid);
14118                }
14119
14120                // A restore should be performed at this point if (a) the install
14121                // succeeded, (b) the operation is not an update, and (c) the new
14122                // package has not opted out of backup participation.
14123                final boolean update = res.removedInfo != null
14124                        && res.removedInfo.removedPackage != null;
14125                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14126                boolean doRestore = !update
14127                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14128
14129                // Set up the post-install work request bookkeeping.  This will be used
14130                // and cleaned up by the post-install event handling regardless of whether
14131                // there's a restore pass performed.  Token values are >= 1.
14132                int token;
14133                if (mNextInstallToken < 0) mNextInstallToken = 1;
14134                token = mNextInstallToken++;
14135
14136                PostInstallData data = new PostInstallData(args, res);
14137                mRunningInstalls.put(token, data);
14138                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14139
14140                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14141                    // Pass responsibility to the Backup Manager.  It will perform a
14142                    // restore if appropriate, then pass responsibility back to the
14143                    // Package Manager to run the post-install observer callbacks
14144                    // and broadcasts.
14145                    IBackupManager bm = IBackupManager.Stub.asInterface(
14146                            ServiceManager.getService(Context.BACKUP_SERVICE));
14147                    if (bm != null) {
14148                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14149                                + " to BM for possible restore");
14150                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14151                        try {
14152                            // TODO: http://b/22388012
14153                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14154                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14155                            } else {
14156                                doRestore = false;
14157                            }
14158                        } catch (RemoteException e) {
14159                            // can't happen; the backup manager is local
14160                        } catch (Exception e) {
14161                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14162                            doRestore = false;
14163                        }
14164                    } else {
14165                        Slog.e(TAG, "Backup Manager not found!");
14166                        doRestore = false;
14167                    }
14168                }
14169
14170                if (!doRestore) {
14171                    // No restore possible, or the Backup Manager was mysteriously not
14172                    // available -- just fire the post-install work request directly.
14173                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14174
14175                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14176
14177                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14178                    mHandler.sendMessage(msg);
14179                }
14180            }
14181        });
14182    }
14183
14184    /**
14185     * Callback from PackageSettings whenever an app is first transitioned out of the
14186     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14187     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14188     * here whether the app is the target of an ongoing install, and only send the
14189     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14190     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14191     * handling.
14192     */
14193    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14194        // Serialize this with the rest of the install-process message chain.  In the
14195        // restore-at-install case, this Runnable will necessarily run before the
14196        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14197        // are coherent.  In the non-restore case, the app has already completed install
14198        // and been launched through some other means, so it is not in a problematic
14199        // state for observers to see the FIRST_LAUNCH signal.
14200        mHandler.post(new Runnable() {
14201            @Override
14202            public void run() {
14203                for (int i = 0; i < mRunningInstalls.size(); i++) {
14204                    final PostInstallData data = mRunningInstalls.valueAt(i);
14205                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14206                        continue;
14207                    }
14208                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14209                        // right package; but is it for the right user?
14210                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14211                            if (userId == data.res.newUsers[uIndex]) {
14212                                if (DEBUG_BACKUP) {
14213                                    Slog.i(TAG, "Package " + pkgName
14214                                            + " being restored so deferring FIRST_LAUNCH");
14215                                }
14216                                return;
14217                            }
14218                        }
14219                    }
14220                }
14221                // didn't find it, so not being restored
14222                if (DEBUG_BACKUP) {
14223                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14224                }
14225                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14226            }
14227        });
14228    }
14229
14230    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14231        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14232                installerPkg, null, userIds);
14233    }
14234
14235    private abstract class HandlerParams {
14236        private static final int MAX_RETRIES = 4;
14237
14238        /**
14239         * Number of times startCopy() has been attempted and had a non-fatal
14240         * error.
14241         */
14242        private int mRetries = 0;
14243
14244        /** User handle for the user requesting the information or installation. */
14245        private final UserHandle mUser;
14246        String traceMethod;
14247        int traceCookie;
14248
14249        HandlerParams(UserHandle user) {
14250            mUser = user;
14251        }
14252
14253        UserHandle getUser() {
14254            return mUser;
14255        }
14256
14257        HandlerParams setTraceMethod(String traceMethod) {
14258            this.traceMethod = traceMethod;
14259            return this;
14260        }
14261
14262        HandlerParams setTraceCookie(int traceCookie) {
14263            this.traceCookie = traceCookie;
14264            return this;
14265        }
14266
14267        final boolean startCopy() {
14268            boolean res;
14269            try {
14270                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14271
14272                if (++mRetries > MAX_RETRIES) {
14273                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14274                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14275                    handleServiceError();
14276                    return false;
14277                } else {
14278                    handleStartCopy();
14279                    res = true;
14280                }
14281            } catch (RemoteException e) {
14282                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14283                mHandler.sendEmptyMessage(MCS_RECONNECT);
14284                res = false;
14285            }
14286            handleReturnCode();
14287            return res;
14288        }
14289
14290        final void serviceError() {
14291            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14292            handleServiceError();
14293            handleReturnCode();
14294        }
14295
14296        abstract void handleStartCopy() throws RemoteException;
14297        abstract void handleServiceError();
14298        abstract void handleReturnCode();
14299    }
14300
14301    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14302        for (File path : paths) {
14303            try {
14304                mcs.clearDirectory(path.getAbsolutePath());
14305            } catch (RemoteException e) {
14306            }
14307        }
14308    }
14309
14310    static class OriginInfo {
14311        /**
14312         * Location where install is coming from, before it has been
14313         * copied/renamed into place. This could be a single monolithic APK
14314         * file, or a cluster directory. This location may be untrusted.
14315         */
14316        final File file;
14317        final String cid;
14318
14319        /**
14320         * Flag indicating that {@link #file} or {@link #cid} has already been
14321         * staged, meaning downstream users don't need to defensively copy the
14322         * contents.
14323         */
14324        final boolean staged;
14325
14326        /**
14327         * Flag indicating that {@link #file} or {@link #cid} is an already
14328         * installed app that is being moved.
14329         */
14330        final boolean existing;
14331
14332        final String resolvedPath;
14333        final File resolvedFile;
14334
14335        static OriginInfo fromNothing() {
14336            return new OriginInfo(null, null, false, false);
14337        }
14338
14339        static OriginInfo fromUntrustedFile(File file) {
14340            return new OriginInfo(file, null, false, false);
14341        }
14342
14343        static OriginInfo fromExistingFile(File file) {
14344            return new OriginInfo(file, null, false, true);
14345        }
14346
14347        static OriginInfo fromStagedFile(File file) {
14348            return new OriginInfo(file, null, true, false);
14349        }
14350
14351        static OriginInfo fromStagedContainer(String cid) {
14352            return new OriginInfo(null, cid, true, false);
14353        }
14354
14355        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14356            this.file = file;
14357            this.cid = cid;
14358            this.staged = staged;
14359            this.existing = existing;
14360
14361            if (cid != null) {
14362                resolvedPath = PackageHelper.getSdDir(cid);
14363                resolvedFile = new File(resolvedPath);
14364            } else if (file != null) {
14365                resolvedPath = file.getAbsolutePath();
14366                resolvedFile = file;
14367            } else {
14368                resolvedPath = null;
14369                resolvedFile = null;
14370            }
14371        }
14372    }
14373
14374    static class MoveInfo {
14375        final int moveId;
14376        final String fromUuid;
14377        final String toUuid;
14378        final String packageName;
14379        final String dataAppName;
14380        final int appId;
14381        final String seinfo;
14382        final int targetSdkVersion;
14383
14384        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14385                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14386            this.moveId = moveId;
14387            this.fromUuid = fromUuid;
14388            this.toUuid = toUuid;
14389            this.packageName = packageName;
14390            this.dataAppName = dataAppName;
14391            this.appId = appId;
14392            this.seinfo = seinfo;
14393            this.targetSdkVersion = targetSdkVersion;
14394        }
14395    }
14396
14397    static class VerificationInfo {
14398        /** A constant used to indicate that a uid value is not present. */
14399        public static final int NO_UID = -1;
14400
14401        /** URI referencing where the package was downloaded from. */
14402        final Uri originatingUri;
14403
14404        /** HTTP referrer URI associated with the originatingURI. */
14405        final Uri referrer;
14406
14407        /** UID of the application that the install request originated from. */
14408        final int originatingUid;
14409
14410        /** UID of application requesting the install */
14411        final int installerUid;
14412
14413        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14414            this.originatingUri = originatingUri;
14415            this.referrer = referrer;
14416            this.originatingUid = originatingUid;
14417            this.installerUid = installerUid;
14418        }
14419    }
14420
14421    class InstallParams extends HandlerParams {
14422        final OriginInfo origin;
14423        final MoveInfo move;
14424        final IPackageInstallObserver2 observer;
14425        int installFlags;
14426        final String installerPackageName;
14427        final String volumeUuid;
14428        private InstallArgs mArgs;
14429        private int mRet;
14430        final String packageAbiOverride;
14431        final String[] grantedRuntimePermissions;
14432        final VerificationInfo verificationInfo;
14433        final Certificate[][] certificates;
14434        final int installReason;
14435
14436        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14437                int installFlags, String installerPackageName, String volumeUuid,
14438                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14439                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14440            super(user);
14441            this.origin = origin;
14442            this.move = move;
14443            this.observer = observer;
14444            this.installFlags = installFlags;
14445            this.installerPackageName = installerPackageName;
14446            this.volumeUuid = volumeUuid;
14447            this.verificationInfo = verificationInfo;
14448            this.packageAbiOverride = packageAbiOverride;
14449            this.grantedRuntimePermissions = grantedPermissions;
14450            this.certificates = certificates;
14451            this.installReason = installReason;
14452        }
14453
14454        @Override
14455        public String toString() {
14456            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14457                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14458        }
14459
14460        private int installLocationPolicy(PackageInfoLite pkgLite) {
14461            String packageName = pkgLite.packageName;
14462            int installLocation = pkgLite.installLocation;
14463            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14464            // reader
14465            synchronized (mPackages) {
14466                // Currently installed package which the new package is attempting to replace or
14467                // null if no such package is installed.
14468                PackageParser.Package installedPkg = mPackages.get(packageName);
14469                // Package which currently owns the data which the new package will own if installed.
14470                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14471                // will be null whereas dataOwnerPkg will contain information about the package
14472                // which was uninstalled while keeping its data.
14473                PackageParser.Package dataOwnerPkg = installedPkg;
14474                if (dataOwnerPkg  == null) {
14475                    PackageSetting ps = mSettings.mPackages.get(packageName);
14476                    if (ps != null) {
14477                        dataOwnerPkg = ps.pkg;
14478                    }
14479                }
14480
14481                if (dataOwnerPkg != null) {
14482                    // If installed, the package will get access to data left on the device by its
14483                    // predecessor. As a security measure, this is permited only if this is not a
14484                    // version downgrade or if the predecessor package is marked as debuggable and
14485                    // a downgrade is explicitly requested.
14486                    //
14487                    // On debuggable platform builds, downgrades are permitted even for
14488                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14489                    // not offer security guarantees and thus it's OK to disable some security
14490                    // mechanisms to make debugging/testing easier on those builds. However, even on
14491                    // debuggable builds downgrades of packages are permitted only if requested via
14492                    // installFlags. This is because we aim to keep the behavior of debuggable
14493                    // platform builds as close as possible to the behavior of non-debuggable
14494                    // platform builds.
14495                    final boolean downgradeRequested =
14496                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14497                    final boolean packageDebuggable =
14498                                (dataOwnerPkg.applicationInfo.flags
14499                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14500                    final boolean downgradePermitted =
14501                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14502                    if (!downgradePermitted) {
14503                        try {
14504                            checkDowngrade(dataOwnerPkg, pkgLite);
14505                        } catch (PackageManagerException e) {
14506                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14507                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14508                        }
14509                    }
14510                }
14511
14512                if (installedPkg != null) {
14513                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14514                        // Check for updated system application.
14515                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14516                            if (onSd) {
14517                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14518                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14519                            }
14520                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14521                        } else {
14522                            if (onSd) {
14523                                // Install flag overrides everything.
14524                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14525                            }
14526                            // If current upgrade specifies particular preference
14527                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14528                                // Application explicitly specified internal.
14529                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14530                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14531                                // App explictly prefers external. Let policy decide
14532                            } else {
14533                                // Prefer previous location
14534                                if (isExternal(installedPkg)) {
14535                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14536                                }
14537                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14538                            }
14539                        }
14540                    } else {
14541                        // Invalid install. Return error code
14542                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14543                    }
14544                }
14545            }
14546            // All the special cases have been taken care of.
14547            // Return result based on recommended install location.
14548            if (onSd) {
14549                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14550            }
14551            return pkgLite.recommendedInstallLocation;
14552        }
14553
14554        /*
14555         * Invoke remote method to get package information and install
14556         * location values. Override install location based on default
14557         * policy if needed and then create install arguments based
14558         * on the install location.
14559         */
14560        public void handleStartCopy() throws RemoteException {
14561            int ret = PackageManager.INSTALL_SUCCEEDED;
14562
14563            // If we're already staged, we've firmly committed to an install location
14564            if (origin.staged) {
14565                if (origin.file != null) {
14566                    installFlags |= PackageManager.INSTALL_INTERNAL;
14567                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14568                } else if (origin.cid != null) {
14569                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14570                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14571                } else {
14572                    throw new IllegalStateException("Invalid stage location");
14573                }
14574            }
14575
14576            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14577            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14578            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14579            PackageInfoLite pkgLite = null;
14580
14581            if (onInt && onSd) {
14582                // Check if both bits are set.
14583                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14584                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14585            } else if (onSd && ephemeral) {
14586                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14587                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14588            } else {
14589                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14590                        packageAbiOverride);
14591
14592                if (DEBUG_EPHEMERAL && ephemeral) {
14593                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14594                }
14595
14596                /*
14597                 * If we have too little free space, try to free cache
14598                 * before giving up.
14599                 */
14600                if (!origin.staged && pkgLite.recommendedInstallLocation
14601                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14602                    // TODO: focus freeing disk space on the target device
14603                    final StorageManager storage = StorageManager.from(mContext);
14604                    final long lowThreshold = storage.getStorageLowBytes(
14605                            Environment.getDataDirectory());
14606
14607                    final long sizeBytes = mContainerService.calculateInstalledSize(
14608                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14609
14610                    try {
14611                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14612                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14613                                installFlags, packageAbiOverride);
14614                    } catch (InstallerException e) {
14615                        Slog.w(TAG, "Failed to free cache", e);
14616                    }
14617
14618                    /*
14619                     * The cache free must have deleted the file we
14620                     * downloaded to install.
14621                     *
14622                     * TODO: fix the "freeCache" call to not delete
14623                     *       the file we care about.
14624                     */
14625                    if (pkgLite.recommendedInstallLocation
14626                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14627                        pkgLite.recommendedInstallLocation
14628                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14629                    }
14630                }
14631            }
14632
14633            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14634                int loc = pkgLite.recommendedInstallLocation;
14635                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14636                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14637                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14638                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14639                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14640                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14641                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14642                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14643                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14644                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14645                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14646                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14647                } else {
14648                    // Override with defaults if needed.
14649                    loc = installLocationPolicy(pkgLite);
14650                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14651                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14652                    } else if (!onSd && !onInt) {
14653                        // Override install location with flags
14654                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14655                            // Set the flag to install on external media.
14656                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14657                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14658                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14659                            if (DEBUG_EPHEMERAL) {
14660                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14661                            }
14662                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14663                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14664                                    |PackageManager.INSTALL_INTERNAL);
14665                        } else {
14666                            // Make sure the flag for installing on external
14667                            // media is unset
14668                            installFlags |= PackageManager.INSTALL_INTERNAL;
14669                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14670                        }
14671                    }
14672                }
14673            }
14674
14675            final InstallArgs args = createInstallArgs(this);
14676            mArgs = args;
14677
14678            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14679                // TODO: http://b/22976637
14680                // Apps installed for "all" users use the device owner to verify the app
14681                UserHandle verifierUser = getUser();
14682                if (verifierUser == UserHandle.ALL) {
14683                    verifierUser = UserHandle.SYSTEM;
14684                }
14685
14686                /*
14687                 * Determine if we have any installed package verifiers. If we
14688                 * do, then we'll defer to them to verify the packages.
14689                 */
14690                final int requiredUid = mRequiredVerifierPackage == null ? -1
14691                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14692                                verifierUser.getIdentifier());
14693                if (!origin.existing && requiredUid != -1
14694                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14695                    final Intent verification = new Intent(
14696                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14697                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14698                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14699                            PACKAGE_MIME_TYPE);
14700                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14701
14702                    // Query all live verifiers based on current user state
14703                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14704                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14705
14706                    if (DEBUG_VERIFY) {
14707                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14708                                + verification.toString() + " with " + pkgLite.verifiers.length
14709                                + " optional verifiers");
14710                    }
14711
14712                    final int verificationId = mPendingVerificationToken++;
14713
14714                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14715
14716                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14717                            installerPackageName);
14718
14719                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14720                            installFlags);
14721
14722                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14723                            pkgLite.packageName);
14724
14725                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14726                            pkgLite.versionCode);
14727
14728                    if (verificationInfo != null) {
14729                        if (verificationInfo.originatingUri != null) {
14730                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14731                                    verificationInfo.originatingUri);
14732                        }
14733                        if (verificationInfo.referrer != null) {
14734                            verification.putExtra(Intent.EXTRA_REFERRER,
14735                                    verificationInfo.referrer);
14736                        }
14737                        if (verificationInfo.originatingUid >= 0) {
14738                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14739                                    verificationInfo.originatingUid);
14740                        }
14741                        if (verificationInfo.installerUid >= 0) {
14742                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14743                                    verificationInfo.installerUid);
14744                        }
14745                    }
14746
14747                    final PackageVerificationState verificationState = new PackageVerificationState(
14748                            requiredUid, args);
14749
14750                    mPendingVerification.append(verificationId, verificationState);
14751
14752                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14753                            receivers, verificationState);
14754
14755                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14756                    final long idleDuration = getVerificationTimeout();
14757
14758                    /*
14759                     * If any sufficient verifiers were listed in the package
14760                     * manifest, attempt to ask them.
14761                     */
14762                    if (sufficientVerifiers != null) {
14763                        final int N = sufficientVerifiers.size();
14764                        if (N == 0) {
14765                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14766                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14767                        } else {
14768                            for (int i = 0; i < N; i++) {
14769                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14770                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14771                                        verifierComponent.getPackageName(), idleDuration,
14772                                        verifierUser.getIdentifier(), false, "package verifier");
14773
14774                                final Intent sufficientIntent = new Intent(verification);
14775                                sufficientIntent.setComponent(verifierComponent);
14776                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14777                            }
14778                        }
14779                    }
14780
14781                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14782                            mRequiredVerifierPackage, receivers);
14783                    if (ret == PackageManager.INSTALL_SUCCEEDED
14784                            && mRequiredVerifierPackage != null) {
14785                        Trace.asyncTraceBegin(
14786                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14787                        /*
14788                         * Send the intent to the required verification agent,
14789                         * but only start the verification timeout after the
14790                         * target BroadcastReceivers have run.
14791                         */
14792                        verification.setComponent(requiredVerifierComponent);
14793                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14794                                mRequiredVerifierPackage, idleDuration,
14795                                verifierUser.getIdentifier(), false, "package verifier");
14796                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14797                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14798                                new BroadcastReceiver() {
14799                                    @Override
14800                                    public void onReceive(Context context, Intent intent) {
14801                                        final Message msg = mHandler
14802                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14803                                        msg.arg1 = verificationId;
14804                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14805                                    }
14806                                }, null, 0, null, null);
14807
14808                        /*
14809                         * We don't want the copy to proceed until verification
14810                         * succeeds, so null out this field.
14811                         */
14812                        mArgs = null;
14813                    }
14814                } else {
14815                    /*
14816                     * No package verification is enabled, so immediately start
14817                     * the remote call to initiate copy using temporary file.
14818                     */
14819                    ret = args.copyApk(mContainerService, true);
14820                }
14821            }
14822
14823            mRet = ret;
14824        }
14825
14826        @Override
14827        void handleReturnCode() {
14828            // If mArgs is null, then MCS couldn't be reached. When it
14829            // reconnects, it will try again to install. At that point, this
14830            // will succeed.
14831            if (mArgs != null) {
14832                processPendingInstall(mArgs, mRet);
14833            }
14834        }
14835
14836        @Override
14837        void handleServiceError() {
14838            mArgs = createInstallArgs(this);
14839            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14840        }
14841
14842        public boolean isForwardLocked() {
14843            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14844        }
14845    }
14846
14847    /**
14848     * Used during creation of InstallArgs
14849     *
14850     * @param installFlags package installation flags
14851     * @return true if should be installed on external storage
14852     */
14853    private static boolean installOnExternalAsec(int installFlags) {
14854        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14855            return false;
14856        }
14857        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14858            return true;
14859        }
14860        return false;
14861    }
14862
14863    /**
14864     * Used during creation of InstallArgs
14865     *
14866     * @param installFlags package installation flags
14867     * @return true if should be installed as forward locked
14868     */
14869    private static boolean installForwardLocked(int installFlags) {
14870        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14871    }
14872
14873    private InstallArgs createInstallArgs(InstallParams params) {
14874        if (params.move != null) {
14875            return new MoveInstallArgs(params);
14876        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14877            return new AsecInstallArgs(params);
14878        } else {
14879            return new FileInstallArgs(params);
14880        }
14881    }
14882
14883    /**
14884     * Create args that describe an existing installed package. Typically used
14885     * when cleaning up old installs, or used as a move source.
14886     */
14887    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14888            String resourcePath, String[] instructionSets) {
14889        final boolean isInAsec;
14890        if (installOnExternalAsec(installFlags)) {
14891            /* Apps on SD card are always in ASEC containers. */
14892            isInAsec = true;
14893        } else if (installForwardLocked(installFlags)
14894                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14895            /*
14896             * Forward-locked apps are only in ASEC containers if they're the
14897             * new style
14898             */
14899            isInAsec = true;
14900        } else {
14901            isInAsec = false;
14902        }
14903
14904        if (isInAsec) {
14905            return new AsecInstallArgs(codePath, instructionSets,
14906                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14907        } else {
14908            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14909        }
14910    }
14911
14912    static abstract class InstallArgs {
14913        /** @see InstallParams#origin */
14914        final OriginInfo origin;
14915        /** @see InstallParams#move */
14916        final MoveInfo move;
14917
14918        final IPackageInstallObserver2 observer;
14919        // Always refers to PackageManager flags only
14920        final int installFlags;
14921        final String installerPackageName;
14922        final String volumeUuid;
14923        final UserHandle user;
14924        final String abiOverride;
14925        final String[] installGrantPermissions;
14926        /** If non-null, drop an async trace when the install completes */
14927        final String traceMethod;
14928        final int traceCookie;
14929        final Certificate[][] certificates;
14930        final int installReason;
14931
14932        // The list of instruction sets supported by this app. This is currently
14933        // only used during the rmdex() phase to clean up resources. We can get rid of this
14934        // if we move dex files under the common app path.
14935        /* nullable */ String[] instructionSets;
14936
14937        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14938                int installFlags, String installerPackageName, String volumeUuid,
14939                UserHandle user, String[] instructionSets,
14940                String abiOverride, String[] installGrantPermissions,
14941                String traceMethod, int traceCookie, Certificate[][] certificates,
14942                int installReason) {
14943            this.origin = origin;
14944            this.move = move;
14945            this.installFlags = installFlags;
14946            this.observer = observer;
14947            this.installerPackageName = installerPackageName;
14948            this.volumeUuid = volumeUuid;
14949            this.user = user;
14950            this.instructionSets = instructionSets;
14951            this.abiOverride = abiOverride;
14952            this.installGrantPermissions = installGrantPermissions;
14953            this.traceMethod = traceMethod;
14954            this.traceCookie = traceCookie;
14955            this.certificates = certificates;
14956            this.installReason = installReason;
14957        }
14958
14959        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14960        abstract int doPreInstall(int status);
14961
14962        /**
14963         * Rename package into final resting place. All paths on the given
14964         * scanned package should be updated to reflect the rename.
14965         */
14966        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14967        abstract int doPostInstall(int status, int uid);
14968
14969        /** @see PackageSettingBase#codePathString */
14970        abstract String getCodePath();
14971        /** @see PackageSettingBase#resourcePathString */
14972        abstract String getResourcePath();
14973
14974        // Need installer lock especially for dex file removal.
14975        abstract void cleanUpResourcesLI();
14976        abstract boolean doPostDeleteLI(boolean delete);
14977
14978        /**
14979         * Called before the source arguments are copied. This is used mostly
14980         * for MoveParams when it needs to read the source file to put it in the
14981         * destination.
14982         */
14983        int doPreCopy() {
14984            return PackageManager.INSTALL_SUCCEEDED;
14985        }
14986
14987        /**
14988         * Called after the source arguments are copied. This is used mostly for
14989         * MoveParams when it needs to read the source file to put it in the
14990         * destination.
14991         */
14992        int doPostCopy(int uid) {
14993            return PackageManager.INSTALL_SUCCEEDED;
14994        }
14995
14996        protected boolean isFwdLocked() {
14997            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14998        }
14999
15000        protected boolean isExternalAsec() {
15001            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15002        }
15003
15004        protected boolean isEphemeral() {
15005            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15006        }
15007
15008        UserHandle getUser() {
15009            return user;
15010        }
15011    }
15012
15013    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15014        if (!allCodePaths.isEmpty()) {
15015            if (instructionSets == null) {
15016                throw new IllegalStateException("instructionSet == null");
15017            }
15018            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15019            for (String codePath : allCodePaths) {
15020                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15021                    try {
15022                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15023                    } catch (InstallerException ignored) {
15024                    }
15025                }
15026            }
15027        }
15028    }
15029
15030    /**
15031     * Logic to handle installation of non-ASEC applications, including copying
15032     * and renaming logic.
15033     */
15034    class FileInstallArgs extends InstallArgs {
15035        private File codeFile;
15036        private File resourceFile;
15037
15038        // Example topology:
15039        // /data/app/com.example/base.apk
15040        // /data/app/com.example/split_foo.apk
15041        // /data/app/com.example/lib/arm/libfoo.so
15042        // /data/app/com.example/lib/arm64/libfoo.so
15043        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15044
15045        /** New install */
15046        FileInstallArgs(InstallParams params) {
15047            super(params.origin, params.move, params.observer, params.installFlags,
15048                    params.installerPackageName, params.volumeUuid,
15049                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15050                    params.grantedRuntimePermissions,
15051                    params.traceMethod, params.traceCookie, params.certificates,
15052                    params.installReason);
15053            if (isFwdLocked()) {
15054                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15055            }
15056        }
15057
15058        /** Existing install */
15059        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15060            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15061                    null, null, null, 0, null /*certificates*/,
15062                    PackageManager.INSTALL_REASON_UNKNOWN);
15063            this.codeFile = (codePath != null) ? new File(codePath) : null;
15064            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15065        }
15066
15067        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15068            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15069            try {
15070                return doCopyApk(imcs, temp);
15071            } finally {
15072                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15073            }
15074        }
15075
15076        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15077            if (origin.staged) {
15078                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15079                codeFile = origin.file;
15080                resourceFile = origin.file;
15081                return PackageManager.INSTALL_SUCCEEDED;
15082            }
15083
15084            try {
15085                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15086                final File tempDir =
15087                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15088                codeFile = tempDir;
15089                resourceFile = tempDir;
15090            } catch (IOException e) {
15091                Slog.w(TAG, "Failed to create copy file: " + e);
15092                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15093            }
15094
15095            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15096                @Override
15097                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15098                    if (!FileUtils.isValidExtFilename(name)) {
15099                        throw new IllegalArgumentException("Invalid filename: " + name);
15100                    }
15101                    try {
15102                        final File file = new File(codeFile, name);
15103                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15104                                O_RDWR | O_CREAT, 0644);
15105                        Os.chmod(file.getAbsolutePath(), 0644);
15106                        return new ParcelFileDescriptor(fd);
15107                    } catch (ErrnoException e) {
15108                        throw new RemoteException("Failed to open: " + e.getMessage());
15109                    }
15110                }
15111            };
15112
15113            int ret = PackageManager.INSTALL_SUCCEEDED;
15114            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15115            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15116                Slog.e(TAG, "Failed to copy package");
15117                return ret;
15118            }
15119
15120            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15121            NativeLibraryHelper.Handle handle = null;
15122            try {
15123                handle = NativeLibraryHelper.Handle.create(codeFile);
15124                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15125                        abiOverride);
15126            } catch (IOException e) {
15127                Slog.e(TAG, "Copying native libraries failed", e);
15128                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15129            } finally {
15130                IoUtils.closeQuietly(handle);
15131            }
15132
15133            return ret;
15134        }
15135
15136        int doPreInstall(int status) {
15137            if (status != PackageManager.INSTALL_SUCCEEDED) {
15138                cleanUp();
15139            }
15140            return status;
15141        }
15142
15143        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15144            if (status != PackageManager.INSTALL_SUCCEEDED) {
15145                cleanUp();
15146                return false;
15147            }
15148
15149            final File targetDir = codeFile.getParentFile();
15150            final File beforeCodeFile = codeFile;
15151            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15152
15153            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15154            try {
15155                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15156            } catch (ErrnoException e) {
15157                Slog.w(TAG, "Failed to rename", e);
15158                return false;
15159            }
15160
15161            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15162                Slog.w(TAG, "Failed to restorecon");
15163                return false;
15164            }
15165
15166            // Reflect the rename internally
15167            codeFile = afterCodeFile;
15168            resourceFile = afterCodeFile;
15169
15170            // Reflect the rename in scanned details
15171            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15172            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15173                    afterCodeFile, pkg.baseCodePath));
15174            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15175                    afterCodeFile, pkg.splitCodePaths));
15176
15177            // Reflect the rename in app info
15178            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15179            pkg.setApplicationInfoCodePath(pkg.codePath);
15180            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15181            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15182            pkg.setApplicationInfoResourcePath(pkg.codePath);
15183            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15184            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15185
15186            return true;
15187        }
15188
15189        int doPostInstall(int status, int uid) {
15190            if (status != PackageManager.INSTALL_SUCCEEDED) {
15191                cleanUp();
15192            }
15193            return status;
15194        }
15195
15196        @Override
15197        String getCodePath() {
15198            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15199        }
15200
15201        @Override
15202        String getResourcePath() {
15203            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15204        }
15205
15206        private boolean cleanUp() {
15207            if (codeFile == null || !codeFile.exists()) {
15208                return false;
15209            }
15210
15211            removeCodePathLI(codeFile);
15212
15213            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15214                resourceFile.delete();
15215            }
15216
15217            return true;
15218        }
15219
15220        void cleanUpResourcesLI() {
15221            // Try enumerating all code paths before deleting
15222            List<String> allCodePaths = Collections.EMPTY_LIST;
15223            if (codeFile != null && codeFile.exists()) {
15224                try {
15225                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15226                    allCodePaths = pkg.getAllCodePaths();
15227                } catch (PackageParserException e) {
15228                    // Ignored; we tried our best
15229                }
15230            }
15231
15232            cleanUp();
15233            removeDexFiles(allCodePaths, instructionSets);
15234        }
15235
15236        boolean doPostDeleteLI(boolean delete) {
15237            // XXX err, shouldn't we respect the delete flag?
15238            cleanUpResourcesLI();
15239            return true;
15240        }
15241    }
15242
15243    private boolean isAsecExternal(String cid) {
15244        final String asecPath = PackageHelper.getSdFilesystem(cid);
15245        return !asecPath.startsWith(mAsecInternalPath);
15246    }
15247
15248    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15249            PackageManagerException {
15250        if (copyRet < 0) {
15251            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15252                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15253                throw new PackageManagerException(copyRet, message);
15254            }
15255        }
15256    }
15257
15258    /**
15259     * Extract the StorageManagerService "container ID" from the full code path of an
15260     * .apk.
15261     */
15262    static String cidFromCodePath(String fullCodePath) {
15263        int eidx = fullCodePath.lastIndexOf("/");
15264        String subStr1 = fullCodePath.substring(0, eidx);
15265        int sidx = subStr1.lastIndexOf("/");
15266        return subStr1.substring(sidx+1, eidx);
15267    }
15268
15269    /**
15270     * Logic to handle installation of ASEC applications, including copying and
15271     * renaming logic.
15272     */
15273    class AsecInstallArgs extends InstallArgs {
15274        static final String RES_FILE_NAME = "pkg.apk";
15275        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15276
15277        String cid;
15278        String packagePath;
15279        String resourcePath;
15280
15281        /** New install */
15282        AsecInstallArgs(InstallParams params) {
15283            super(params.origin, params.move, params.observer, params.installFlags,
15284                    params.installerPackageName, params.volumeUuid,
15285                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15286                    params.grantedRuntimePermissions,
15287                    params.traceMethod, params.traceCookie, params.certificates,
15288                    params.installReason);
15289        }
15290
15291        /** Existing install */
15292        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15293                        boolean isExternal, boolean isForwardLocked) {
15294            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15295                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15296                    instructionSets, null, null, null, 0, null /*certificates*/,
15297                    PackageManager.INSTALL_REASON_UNKNOWN);
15298            // Hackily pretend we're still looking at a full code path
15299            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15300                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15301            }
15302
15303            // Extract cid from fullCodePath
15304            int eidx = fullCodePath.lastIndexOf("/");
15305            String subStr1 = fullCodePath.substring(0, eidx);
15306            int sidx = subStr1.lastIndexOf("/");
15307            cid = subStr1.substring(sidx+1, eidx);
15308            setMountPath(subStr1);
15309        }
15310
15311        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15312            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15313                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15314                    instructionSets, null, null, null, 0, null /*certificates*/,
15315                    PackageManager.INSTALL_REASON_UNKNOWN);
15316            this.cid = cid;
15317            setMountPath(PackageHelper.getSdDir(cid));
15318        }
15319
15320        void createCopyFile() {
15321            cid = mInstallerService.allocateExternalStageCidLegacy();
15322        }
15323
15324        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15325            if (origin.staged && origin.cid != null) {
15326                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15327                cid = origin.cid;
15328                setMountPath(PackageHelper.getSdDir(cid));
15329                return PackageManager.INSTALL_SUCCEEDED;
15330            }
15331
15332            if (temp) {
15333                createCopyFile();
15334            } else {
15335                /*
15336                 * Pre-emptively destroy the container since it's destroyed if
15337                 * copying fails due to it existing anyway.
15338                 */
15339                PackageHelper.destroySdDir(cid);
15340            }
15341
15342            final String newMountPath = imcs.copyPackageToContainer(
15343                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15344                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15345
15346            if (newMountPath != null) {
15347                setMountPath(newMountPath);
15348                return PackageManager.INSTALL_SUCCEEDED;
15349            } else {
15350                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15351            }
15352        }
15353
15354        @Override
15355        String getCodePath() {
15356            return packagePath;
15357        }
15358
15359        @Override
15360        String getResourcePath() {
15361            return resourcePath;
15362        }
15363
15364        int doPreInstall(int status) {
15365            if (status != PackageManager.INSTALL_SUCCEEDED) {
15366                // Destroy container
15367                PackageHelper.destroySdDir(cid);
15368            } else {
15369                boolean mounted = PackageHelper.isContainerMounted(cid);
15370                if (!mounted) {
15371                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15372                            Process.SYSTEM_UID);
15373                    if (newMountPath != null) {
15374                        setMountPath(newMountPath);
15375                    } else {
15376                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15377                    }
15378                }
15379            }
15380            return status;
15381        }
15382
15383        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15384            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15385            String newMountPath = null;
15386            if (PackageHelper.isContainerMounted(cid)) {
15387                // Unmount the container
15388                if (!PackageHelper.unMountSdDir(cid)) {
15389                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15390                    return false;
15391                }
15392            }
15393            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15394                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15395                        " which might be stale. Will try to clean up.");
15396                // Clean up the stale container and proceed to recreate.
15397                if (!PackageHelper.destroySdDir(newCacheId)) {
15398                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15399                    return false;
15400                }
15401                // Successfully cleaned up stale container. Try to rename again.
15402                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15403                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15404                            + " inspite of cleaning it up.");
15405                    return false;
15406                }
15407            }
15408            if (!PackageHelper.isContainerMounted(newCacheId)) {
15409                Slog.w(TAG, "Mounting container " + newCacheId);
15410                newMountPath = PackageHelper.mountSdDir(newCacheId,
15411                        getEncryptKey(), Process.SYSTEM_UID);
15412            } else {
15413                newMountPath = PackageHelper.getSdDir(newCacheId);
15414            }
15415            if (newMountPath == null) {
15416                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15417                return false;
15418            }
15419            Log.i(TAG, "Succesfully renamed " + cid +
15420                    " to " + newCacheId +
15421                    " at new path: " + newMountPath);
15422            cid = newCacheId;
15423
15424            final File beforeCodeFile = new File(packagePath);
15425            setMountPath(newMountPath);
15426            final File afterCodeFile = new File(packagePath);
15427
15428            // Reflect the rename in scanned details
15429            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15430            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15431                    afterCodeFile, pkg.baseCodePath));
15432            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15433                    afterCodeFile, pkg.splitCodePaths));
15434
15435            // Reflect the rename in app info
15436            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15437            pkg.setApplicationInfoCodePath(pkg.codePath);
15438            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15439            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15440            pkg.setApplicationInfoResourcePath(pkg.codePath);
15441            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15442            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15443
15444            return true;
15445        }
15446
15447        private void setMountPath(String mountPath) {
15448            final File mountFile = new File(mountPath);
15449
15450            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15451            if (monolithicFile.exists()) {
15452                packagePath = monolithicFile.getAbsolutePath();
15453                if (isFwdLocked()) {
15454                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15455                } else {
15456                    resourcePath = packagePath;
15457                }
15458            } else {
15459                packagePath = mountFile.getAbsolutePath();
15460                resourcePath = packagePath;
15461            }
15462        }
15463
15464        int doPostInstall(int status, int uid) {
15465            if (status != PackageManager.INSTALL_SUCCEEDED) {
15466                cleanUp();
15467            } else {
15468                final int groupOwner;
15469                final String protectedFile;
15470                if (isFwdLocked()) {
15471                    groupOwner = UserHandle.getSharedAppGid(uid);
15472                    protectedFile = RES_FILE_NAME;
15473                } else {
15474                    groupOwner = -1;
15475                    protectedFile = null;
15476                }
15477
15478                if (uid < Process.FIRST_APPLICATION_UID
15479                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15480                    Slog.e(TAG, "Failed to finalize " + cid);
15481                    PackageHelper.destroySdDir(cid);
15482                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15483                }
15484
15485                boolean mounted = PackageHelper.isContainerMounted(cid);
15486                if (!mounted) {
15487                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15488                }
15489            }
15490            return status;
15491        }
15492
15493        private void cleanUp() {
15494            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15495
15496            // Destroy secure container
15497            PackageHelper.destroySdDir(cid);
15498        }
15499
15500        private List<String> getAllCodePaths() {
15501            final File codeFile = new File(getCodePath());
15502            if (codeFile != null && codeFile.exists()) {
15503                try {
15504                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15505                    return pkg.getAllCodePaths();
15506                } catch (PackageParserException e) {
15507                    // Ignored; we tried our best
15508                }
15509            }
15510            return Collections.EMPTY_LIST;
15511        }
15512
15513        void cleanUpResourcesLI() {
15514            // Enumerate all code paths before deleting
15515            cleanUpResourcesLI(getAllCodePaths());
15516        }
15517
15518        private void cleanUpResourcesLI(List<String> allCodePaths) {
15519            cleanUp();
15520            removeDexFiles(allCodePaths, instructionSets);
15521        }
15522
15523        String getPackageName() {
15524            return getAsecPackageName(cid);
15525        }
15526
15527        boolean doPostDeleteLI(boolean delete) {
15528            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15529            final List<String> allCodePaths = getAllCodePaths();
15530            boolean mounted = PackageHelper.isContainerMounted(cid);
15531            if (mounted) {
15532                // Unmount first
15533                if (PackageHelper.unMountSdDir(cid)) {
15534                    mounted = false;
15535                }
15536            }
15537            if (!mounted && delete) {
15538                cleanUpResourcesLI(allCodePaths);
15539            }
15540            return !mounted;
15541        }
15542
15543        @Override
15544        int doPreCopy() {
15545            if (isFwdLocked()) {
15546                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15547                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15548                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15549                }
15550            }
15551
15552            return PackageManager.INSTALL_SUCCEEDED;
15553        }
15554
15555        @Override
15556        int doPostCopy(int uid) {
15557            if (isFwdLocked()) {
15558                if (uid < Process.FIRST_APPLICATION_UID
15559                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15560                                RES_FILE_NAME)) {
15561                    Slog.e(TAG, "Failed to finalize " + cid);
15562                    PackageHelper.destroySdDir(cid);
15563                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15564                }
15565            }
15566
15567            return PackageManager.INSTALL_SUCCEEDED;
15568        }
15569    }
15570
15571    /**
15572     * Logic to handle movement of existing installed applications.
15573     */
15574    class MoveInstallArgs extends InstallArgs {
15575        private File codeFile;
15576        private File resourceFile;
15577
15578        /** New install */
15579        MoveInstallArgs(InstallParams params) {
15580            super(params.origin, params.move, params.observer, params.installFlags,
15581                    params.installerPackageName, params.volumeUuid,
15582                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15583                    params.grantedRuntimePermissions,
15584                    params.traceMethod, params.traceCookie, params.certificates,
15585                    params.installReason);
15586        }
15587
15588        int copyApk(IMediaContainerService imcs, boolean temp) {
15589            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15590                    + move.fromUuid + " to " + move.toUuid);
15591            synchronized (mInstaller) {
15592                try {
15593                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15594                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15595                } catch (InstallerException e) {
15596                    Slog.w(TAG, "Failed to move app", e);
15597                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15598                }
15599            }
15600
15601            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15602            resourceFile = codeFile;
15603            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15604
15605            return PackageManager.INSTALL_SUCCEEDED;
15606        }
15607
15608        int doPreInstall(int status) {
15609            if (status != PackageManager.INSTALL_SUCCEEDED) {
15610                cleanUp(move.toUuid);
15611            }
15612            return status;
15613        }
15614
15615        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15616            if (status != PackageManager.INSTALL_SUCCEEDED) {
15617                cleanUp(move.toUuid);
15618                return false;
15619            }
15620
15621            // Reflect the move in app info
15622            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15623            pkg.setApplicationInfoCodePath(pkg.codePath);
15624            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15625            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15626            pkg.setApplicationInfoResourcePath(pkg.codePath);
15627            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15628            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15629
15630            return true;
15631        }
15632
15633        int doPostInstall(int status, int uid) {
15634            if (status == PackageManager.INSTALL_SUCCEEDED) {
15635                cleanUp(move.fromUuid);
15636            } else {
15637                cleanUp(move.toUuid);
15638            }
15639            return status;
15640        }
15641
15642        @Override
15643        String getCodePath() {
15644            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15645        }
15646
15647        @Override
15648        String getResourcePath() {
15649            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15650        }
15651
15652        private boolean cleanUp(String volumeUuid) {
15653            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15654                    move.dataAppName);
15655            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15656            final int[] userIds = sUserManager.getUserIds();
15657            synchronized (mInstallLock) {
15658                // Clean up both app data and code
15659                // All package moves are frozen until finished
15660                for (int userId : userIds) {
15661                    try {
15662                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15663                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15664                    } catch (InstallerException e) {
15665                        Slog.w(TAG, String.valueOf(e));
15666                    }
15667                }
15668                removeCodePathLI(codeFile);
15669            }
15670            return true;
15671        }
15672
15673        void cleanUpResourcesLI() {
15674            throw new UnsupportedOperationException();
15675        }
15676
15677        boolean doPostDeleteLI(boolean delete) {
15678            throw new UnsupportedOperationException();
15679        }
15680    }
15681
15682    static String getAsecPackageName(String packageCid) {
15683        int idx = packageCid.lastIndexOf("-");
15684        if (idx == -1) {
15685            return packageCid;
15686        }
15687        return packageCid.substring(0, idx);
15688    }
15689
15690    // Utility method used to create code paths based on package name and available index.
15691    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15692        String idxStr = "";
15693        int idx = 1;
15694        // Fall back to default value of idx=1 if prefix is not
15695        // part of oldCodePath
15696        if (oldCodePath != null) {
15697            String subStr = oldCodePath;
15698            // Drop the suffix right away
15699            if (suffix != null && subStr.endsWith(suffix)) {
15700                subStr = subStr.substring(0, subStr.length() - suffix.length());
15701            }
15702            // If oldCodePath already contains prefix find out the
15703            // ending index to either increment or decrement.
15704            int sidx = subStr.lastIndexOf(prefix);
15705            if (sidx != -1) {
15706                subStr = subStr.substring(sidx + prefix.length());
15707                if (subStr != null) {
15708                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15709                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15710                    }
15711                    try {
15712                        idx = Integer.parseInt(subStr);
15713                        if (idx <= 1) {
15714                            idx++;
15715                        } else {
15716                            idx--;
15717                        }
15718                    } catch(NumberFormatException e) {
15719                    }
15720                }
15721            }
15722        }
15723        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15724        return prefix + idxStr;
15725    }
15726
15727    private File getNextCodePath(File targetDir, String packageName) {
15728        File result;
15729        SecureRandom random = new SecureRandom();
15730        byte[] bytes = new byte[16];
15731        do {
15732            random.nextBytes(bytes);
15733            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15734            result = new File(targetDir, packageName + "-" + suffix);
15735        } while (result.exists());
15736        return result;
15737    }
15738
15739    // Utility method that returns the relative package path with respect
15740    // to the installation directory. Like say for /data/data/com.test-1.apk
15741    // string com.test-1 is returned.
15742    static String deriveCodePathName(String codePath) {
15743        if (codePath == null) {
15744            return null;
15745        }
15746        final File codeFile = new File(codePath);
15747        final String name = codeFile.getName();
15748        if (codeFile.isDirectory()) {
15749            return name;
15750        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15751            final int lastDot = name.lastIndexOf('.');
15752            return name.substring(0, lastDot);
15753        } else {
15754            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15755            return null;
15756        }
15757    }
15758
15759    static class PackageInstalledInfo {
15760        String name;
15761        int uid;
15762        // The set of users that originally had this package installed.
15763        int[] origUsers;
15764        // The set of users that now have this package installed.
15765        int[] newUsers;
15766        PackageParser.Package pkg;
15767        int returnCode;
15768        String returnMsg;
15769        PackageRemovedInfo removedInfo;
15770        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15771
15772        public void setError(int code, String msg) {
15773            setReturnCode(code);
15774            setReturnMessage(msg);
15775            Slog.w(TAG, msg);
15776        }
15777
15778        public void setError(String msg, PackageParserException e) {
15779            setReturnCode(e.error);
15780            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15781            Slog.w(TAG, msg, e);
15782        }
15783
15784        public void setError(String msg, PackageManagerException e) {
15785            returnCode = e.error;
15786            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15787            Slog.w(TAG, msg, e);
15788        }
15789
15790        public void setReturnCode(int returnCode) {
15791            this.returnCode = returnCode;
15792            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15793            for (int i = 0; i < childCount; i++) {
15794                addedChildPackages.valueAt(i).returnCode = returnCode;
15795            }
15796        }
15797
15798        private void setReturnMessage(String returnMsg) {
15799            this.returnMsg = returnMsg;
15800            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15801            for (int i = 0; i < childCount; i++) {
15802                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15803            }
15804        }
15805
15806        // In some error cases we want to convey more info back to the observer
15807        String origPackage;
15808        String origPermission;
15809    }
15810
15811    /*
15812     * Install a non-existing package.
15813     */
15814    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15815            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15816            PackageInstalledInfo res, int installReason) {
15817        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15818
15819        // Remember this for later, in case we need to rollback this install
15820        String pkgName = pkg.packageName;
15821
15822        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15823
15824        synchronized(mPackages) {
15825            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15826            if (renamedPackage != null) {
15827                // A package with the same name is already installed, though
15828                // it has been renamed to an older name.  The package we
15829                // are trying to install should be installed as an update to
15830                // the existing one, but that has not been requested, so bail.
15831                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15832                        + " without first uninstalling package running as "
15833                        + renamedPackage);
15834                return;
15835            }
15836            if (mPackages.containsKey(pkgName)) {
15837                // Don't allow installation over an existing package with the same name.
15838                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15839                        + " without first uninstalling.");
15840                return;
15841            }
15842        }
15843
15844        try {
15845            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15846                    System.currentTimeMillis(), user);
15847
15848            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15849
15850            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15851                prepareAppDataAfterInstallLIF(newPackage);
15852
15853            } else {
15854                // Remove package from internal structures, but keep around any
15855                // data that might have already existed
15856                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15857                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15858            }
15859        } catch (PackageManagerException e) {
15860            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15861        }
15862
15863        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15864    }
15865
15866    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15867        // Can't rotate keys during boot or if sharedUser.
15868        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15869                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15870            return false;
15871        }
15872        // app is using upgradeKeySets; make sure all are valid
15873        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15874        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15875        for (int i = 0; i < upgradeKeySets.length; i++) {
15876            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15877                Slog.wtf(TAG, "Package "
15878                         + (oldPs.name != null ? oldPs.name : "<null>")
15879                         + " contains upgrade-key-set reference to unknown key-set: "
15880                         + upgradeKeySets[i]
15881                         + " reverting to signatures check.");
15882                return false;
15883            }
15884        }
15885        return true;
15886    }
15887
15888    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15889        // Upgrade keysets are being used.  Determine if new package has a superset of the
15890        // required keys.
15891        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15892        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15893        for (int i = 0; i < upgradeKeySets.length; i++) {
15894            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15895            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15896                return true;
15897            }
15898        }
15899        return false;
15900    }
15901
15902    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15903        try (DigestInputStream digestStream =
15904                new DigestInputStream(new FileInputStream(file), digest)) {
15905            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15906        }
15907    }
15908
15909    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15910            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15911            int installReason) {
15912        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15913
15914        final PackageParser.Package oldPackage;
15915        final String pkgName = pkg.packageName;
15916        final int[] allUsers;
15917        final int[] installedUsers;
15918
15919        synchronized(mPackages) {
15920            oldPackage = mPackages.get(pkgName);
15921            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15922
15923            // don't allow upgrade to target a release SDK from a pre-release SDK
15924            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15925                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15926            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15927                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15928            if (oldTargetsPreRelease
15929                    && !newTargetsPreRelease
15930                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15931                Slog.w(TAG, "Can't install package targeting released sdk");
15932                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15933                return;
15934            }
15935
15936            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15937
15938            // verify signatures are valid
15939            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15940                if (!checkUpgradeKeySetLP(ps, pkg)) {
15941                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15942                            "New package not signed by keys specified by upgrade-keysets: "
15943                                    + pkgName);
15944                    return;
15945                }
15946            } else {
15947                // default to original signature matching
15948                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15949                        != PackageManager.SIGNATURE_MATCH) {
15950                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15951                            "New package has a different signature: " + pkgName);
15952                    return;
15953                }
15954            }
15955
15956            // don't allow a system upgrade unless the upgrade hash matches
15957            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15958                byte[] digestBytes = null;
15959                try {
15960                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15961                    updateDigest(digest, new File(pkg.baseCodePath));
15962                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15963                        for (String path : pkg.splitCodePaths) {
15964                            updateDigest(digest, new File(path));
15965                        }
15966                    }
15967                    digestBytes = digest.digest();
15968                } catch (NoSuchAlgorithmException | IOException e) {
15969                    res.setError(INSTALL_FAILED_INVALID_APK,
15970                            "Could not compute hash: " + pkgName);
15971                    return;
15972                }
15973                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15974                    res.setError(INSTALL_FAILED_INVALID_APK,
15975                            "New package fails restrict-update check: " + pkgName);
15976                    return;
15977                }
15978                // retain upgrade restriction
15979                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15980            }
15981
15982            // Check for shared user id changes
15983            String invalidPackageName =
15984                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15985            if (invalidPackageName != null) {
15986                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15987                        "Package " + invalidPackageName + " tried to change user "
15988                                + oldPackage.mSharedUserId);
15989                return;
15990            }
15991
15992            // In case of rollback, remember per-user/profile install state
15993            allUsers = sUserManager.getUserIds();
15994            installedUsers = ps.queryInstalledUsers(allUsers, true);
15995
15996            // don't allow an upgrade from full to ephemeral
15997            if (isInstantApp) {
15998                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15999                    for (int currentUser : allUsers) {
16000                        if (!ps.getInstantApp(currentUser)) {
16001                            // can't downgrade from full to instant
16002                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16003                                    + " for user: " + currentUser);
16004                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16005                            return;
16006                        }
16007                    }
16008                } else if (!ps.getInstantApp(user.getIdentifier())) {
16009                    // can't downgrade from full to instant
16010                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16011                            + " for user: " + user.getIdentifier());
16012                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16013                    return;
16014                }
16015            }
16016        }
16017
16018        // Update what is removed
16019        res.removedInfo = new PackageRemovedInfo();
16020        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16021        res.removedInfo.removedPackage = oldPackage.packageName;
16022        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16023        res.removedInfo.isUpdate = true;
16024        res.removedInfo.origUsers = installedUsers;
16025        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
16026        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16027        for (int i = 0; i < installedUsers.length; i++) {
16028            final int userId = installedUsers[i];
16029            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16030        }
16031
16032        final int childCount = (oldPackage.childPackages != null)
16033                ? oldPackage.childPackages.size() : 0;
16034        for (int i = 0; i < childCount; i++) {
16035            boolean childPackageUpdated = false;
16036            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16037            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16038            if (res.addedChildPackages != null) {
16039                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16040                if (childRes != null) {
16041                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16042                    childRes.removedInfo.removedPackage = childPkg.packageName;
16043                    childRes.removedInfo.isUpdate = true;
16044                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16045                    childPackageUpdated = true;
16046                }
16047            }
16048            if (!childPackageUpdated) {
16049                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16050                childRemovedRes.removedPackage = childPkg.packageName;
16051                childRemovedRes.isUpdate = false;
16052                childRemovedRes.dataRemoved = true;
16053                synchronized (mPackages) {
16054                    if (childPs != null) {
16055                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16056                    }
16057                }
16058                if (res.removedInfo.removedChildPackages == null) {
16059                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16060                }
16061                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16062            }
16063        }
16064
16065        boolean sysPkg = (isSystemApp(oldPackage));
16066        if (sysPkg) {
16067            // Set the system/privileged flags as needed
16068            final boolean privileged =
16069                    (oldPackage.applicationInfo.privateFlags
16070                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16071            final int systemPolicyFlags = policyFlags
16072                    | PackageParser.PARSE_IS_SYSTEM
16073                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16074
16075            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16076                    user, allUsers, installerPackageName, res, installReason);
16077        } else {
16078            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16079                    user, allUsers, installerPackageName, res, installReason);
16080        }
16081    }
16082
16083    public List<String> getPreviousCodePaths(String packageName) {
16084        final PackageSetting ps = mSettings.mPackages.get(packageName);
16085        final List<String> result = new ArrayList<String>();
16086        if (ps != null && ps.oldCodePaths != null) {
16087            result.addAll(ps.oldCodePaths);
16088        }
16089        return result;
16090    }
16091
16092    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16093            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16094            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16095            int installReason) {
16096        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16097                + deletedPackage);
16098
16099        String pkgName = deletedPackage.packageName;
16100        boolean deletedPkg = true;
16101        boolean addedPkg = false;
16102        boolean updatedSettings = false;
16103        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16104        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16105                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16106
16107        final long origUpdateTime = (pkg.mExtras != null)
16108                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16109
16110        // First delete the existing package while retaining the data directory
16111        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16112                res.removedInfo, true, pkg)) {
16113            // If the existing package wasn't successfully deleted
16114            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16115            deletedPkg = false;
16116        } else {
16117            // Successfully deleted the old package; proceed with replace.
16118
16119            // If deleted package lived in a container, give users a chance to
16120            // relinquish resources before killing.
16121            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16122                if (DEBUG_INSTALL) {
16123                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16124                }
16125                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16126                final ArrayList<String> pkgList = new ArrayList<String>(1);
16127                pkgList.add(deletedPackage.applicationInfo.packageName);
16128                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16129            }
16130
16131            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16132                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16133            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16134
16135            try {
16136                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16137                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16138                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16139                        installReason);
16140
16141                // Update the in-memory copy of the previous code paths.
16142                PackageSetting ps = mSettings.mPackages.get(pkgName);
16143                if (!killApp) {
16144                    if (ps.oldCodePaths == null) {
16145                        ps.oldCodePaths = new ArraySet<>();
16146                    }
16147                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16148                    if (deletedPackage.splitCodePaths != null) {
16149                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16150                    }
16151                } else {
16152                    ps.oldCodePaths = null;
16153                }
16154                if (ps.childPackageNames != null) {
16155                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16156                        final String childPkgName = ps.childPackageNames.get(i);
16157                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16158                        childPs.oldCodePaths = ps.oldCodePaths;
16159                    }
16160                }
16161                // set instant app status, but, only if it's explicitly specified
16162                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16163                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16164                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16165                prepareAppDataAfterInstallLIF(newPackage);
16166                addedPkg = true;
16167                mDexManager.notifyPackageUpdated(newPackage.packageName,
16168                        newPackage.baseCodePath, newPackage.splitCodePaths);
16169            } catch (PackageManagerException e) {
16170                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16171            }
16172        }
16173
16174        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16175            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16176
16177            // Revert all internal state mutations and added folders for the failed install
16178            if (addedPkg) {
16179                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16180                        res.removedInfo, true, null);
16181            }
16182
16183            // Restore the old package
16184            if (deletedPkg) {
16185                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16186                File restoreFile = new File(deletedPackage.codePath);
16187                // Parse old package
16188                boolean oldExternal = isExternal(deletedPackage);
16189                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16190                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16191                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16192                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16193                try {
16194                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16195                            null);
16196                } catch (PackageManagerException e) {
16197                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16198                            + e.getMessage());
16199                    return;
16200                }
16201
16202                synchronized (mPackages) {
16203                    // Ensure the installer package name up to date
16204                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16205
16206                    // Update permissions for restored package
16207                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16208
16209                    mSettings.writeLPr();
16210                }
16211
16212                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16213            }
16214        } else {
16215            synchronized (mPackages) {
16216                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16217                if (ps != null) {
16218                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16219                    if (res.removedInfo.removedChildPackages != null) {
16220                        final int childCount = res.removedInfo.removedChildPackages.size();
16221                        // Iterate in reverse as we may modify the collection
16222                        for (int i = childCount - 1; i >= 0; i--) {
16223                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16224                            if (res.addedChildPackages.containsKey(childPackageName)) {
16225                                res.removedInfo.removedChildPackages.removeAt(i);
16226                            } else {
16227                                PackageRemovedInfo childInfo = res.removedInfo
16228                                        .removedChildPackages.valueAt(i);
16229                                childInfo.removedForAllUsers = mPackages.get(
16230                                        childInfo.removedPackage) == null;
16231                            }
16232                        }
16233                    }
16234                }
16235            }
16236        }
16237    }
16238
16239    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16240            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16241            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16242            int installReason) {
16243        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16244                + ", old=" + deletedPackage);
16245
16246        final boolean disabledSystem;
16247
16248        // Remove existing system package
16249        removePackageLI(deletedPackage, true);
16250
16251        synchronized (mPackages) {
16252            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16253        }
16254        if (!disabledSystem) {
16255            // We didn't need to disable the .apk as a current system package,
16256            // which means we are replacing another update that is already
16257            // installed.  We need to make sure to delete the older one's .apk.
16258            res.removedInfo.args = createInstallArgsForExisting(0,
16259                    deletedPackage.applicationInfo.getCodePath(),
16260                    deletedPackage.applicationInfo.getResourcePath(),
16261                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16262        } else {
16263            res.removedInfo.args = null;
16264        }
16265
16266        // Successfully disabled the old package. Now proceed with re-installation
16267        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16268                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16269        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16270
16271        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16272        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16273                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16274
16275        PackageParser.Package newPackage = null;
16276        try {
16277            // Add the package to the internal data structures
16278            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16279
16280            // Set the update and install times
16281            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16282            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16283                    System.currentTimeMillis());
16284
16285            // Update the package dynamic state if succeeded
16286            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16287                // Now that the install succeeded make sure we remove data
16288                // directories for any child package the update removed.
16289                final int deletedChildCount = (deletedPackage.childPackages != null)
16290                        ? deletedPackage.childPackages.size() : 0;
16291                final int newChildCount = (newPackage.childPackages != null)
16292                        ? newPackage.childPackages.size() : 0;
16293                for (int i = 0; i < deletedChildCount; i++) {
16294                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16295                    boolean childPackageDeleted = true;
16296                    for (int j = 0; j < newChildCount; j++) {
16297                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16298                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16299                            childPackageDeleted = false;
16300                            break;
16301                        }
16302                    }
16303                    if (childPackageDeleted) {
16304                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16305                                deletedChildPkg.packageName);
16306                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16307                            PackageRemovedInfo removedChildRes = res.removedInfo
16308                                    .removedChildPackages.get(deletedChildPkg.packageName);
16309                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16310                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16311                        }
16312                    }
16313                }
16314
16315                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16316                        installReason);
16317                prepareAppDataAfterInstallLIF(newPackage);
16318
16319                mDexManager.notifyPackageUpdated(newPackage.packageName,
16320                            newPackage.baseCodePath, newPackage.splitCodePaths);
16321            }
16322        } catch (PackageManagerException e) {
16323            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16324            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16325        }
16326
16327        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16328            // Re installation failed. Restore old information
16329            // Remove new pkg information
16330            if (newPackage != null) {
16331                removeInstalledPackageLI(newPackage, true);
16332            }
16333            // Add back the old system package
16334            try {
16335                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16336            } catch (PackageManagerException e) {
16337                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16338            }
16339
16340            synchronized (mPackages) {
16341                if (disabledSystem) {
16342                    enableSystemPackageLPw(deletedPackage);
16343                }
16344
16345                // Ensure the installer package name up to date
16346                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16347
16348                // Update permissions for restored package
16349                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16350
16351                mSettings.writeLPr();
16352            }
16353
16354            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16355                    + " after failed upgrade");
16356        }
16357    }
16358
16359    /**
16360     * Checks whether the parent or any of the child packages have a change shared
16361     * user. For a package to be a valid update the shred users of the parent and
16362     * the children should match. We may later support changing child shared users.
16363     * @param oldPkg The updated package.
16364     * @param newPkg The update package.
16365     * @return The shared user that change between the versions.
16366     */
16367    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16368            PackageParser.Package newPkg) {
16369        // Check parent shared user
16370        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16371            return newPkg.packageName;
16372        }
16373        // Check child shared users
16374        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16375        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16376        for (int i = 0; i < newChildCount; i++) {
16377            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16378            // If this child was present, did it have the same shared user?
16379            for (int j = 0; j < oldChildCount; j++) {
16380                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16381                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16382                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16383                    return newChildPkg.packageName;
16384                }
16385            }
16386        }
16387        return null;
16388    }
16389
16390    private void removeNativeBinariesLI(PackageSetting ps) {
16391        // Remove the lib path for the parent package
16392        if (ps != null) {
16393            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16394            // Remove the lib path for the child packages
16395            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16396            for (int i = 0; i < childCount; i++) {
16397                PackageSetting childPs = null;
16398                synchronized (mPackages) {
16399                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16400                }
16401                if (childPs != null) {
16402                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16403                            .legacyNativeLibraryPathString);
16404                }
16405            }
16406        }
16407    }
16408
16409    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16410        // Enable the parent package
16411        mSettings.enableSystemPackageLPw(pkg.packageName);
16412        // Enable the child packages
16413        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16414        for (int i = 0; i < childCount; i++) {
16415            PackageParser.Package childPkg = pkg.childPackages.get(i);
16416            mSettings.enableSystemPackageLPw(childPkg.packageName);
16417        }
16418    }
16419
16420    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16421            PackageParser.Package newPkg) {
16422        // Disable the parent package (parent always replaced)
16423        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16424        // Disable the child packages
16425        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16426        for (int i = 0; i < childCount; i++) {
16427            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16428            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16429            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16430        }
16431        return disabled;
16432    }
16433
16434    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16435            String installerPackageName) {
16436        // Enable the parent package
16437        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16438        // Enable the child packages
16439        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16440        for (int i = 0; i < childCount; i++) {
16441            PackageParser.Package childPkg = pkg.childPackages.get(i);
16442            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16443        }
16444    }
16445
16446    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16447        // Collect all used permissions in the UID
16448        ArraySet<String> usedPermissions = new ArraySet<>();
16449        final int packageCount = su.packages.size();
16450        for (int i = 0; i < packageCount; i++) {
16451            PackageSetting ps = su.packages.valueAt(i);
16452            if (ps.pkg == null) {
16453                continue;
16454            }
16455            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16456            for (int j = 0; j < requestedPermCount; j++) {
16457                String permission = ps.pkg.requestedPermissions.get(j);
16458                BasePermission bp = mSettings.mPermissions.get(permission);
16459                if (bp != null) {
16460                    usedPermissions.add(permission);
16461                }
16462            }
16463        }
16464
16465        PermissionsState permissionsState = su.getPermissionsState();
16466        // Prune install permissions
16467        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16468        final int installPermCount = installPermStates.size();
16469        for (int i = installPermCount - 1; i >= 0;  i--) {
16470            PermissionState permissionState = installPermStates.get(i);
16471            if (!usedPermissions.contains(permissionState.getName())) {
16472                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16473                if (bp != null) {
16474                    permissionsState.revokeInstallPermission(bp);
16475                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16476                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16477                }
16478            }
16479        }
16480
16481        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16482
16483        // Prune runtime permissions
16484        for (int userId : allUserIds) {
16485            List<PermissionState> runtimePermStates = permissionsState
16486                    .getRuntimePermissionStates(userId);
16487            final int runtimePermCount = runtimePermStates.size();
16488            for (int i = runtimePermCount - 1; i >= 0; i--) {
16489                PermissionState permissionState = runtimePermStates.get(i);
16490                if (!usedPermissions.contains(permissionState.getName())) {
16491                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16492                    if (bp != null) {
16493                        permissionsState.revokeRuntimePermission(bp, userId);
16494                        permissionsState.updatePermissionFlags(bp, userId,
16495                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16496                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16497                                runtimePermissionChangedUserIds, userId);
16498                    }
16499                }
16500            }
16501        }
16502
16503        return runtimePermissionChangedUserIds;
16504    }
16505
16506    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16507            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16508        // Update the parent package setting
16509        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16510                res, user, installReason);
16511        // Update the child packages setting
16512        final int childCount = (newPackage.childPackages != null)
16513                ? newPackage.childPackages.size() : 0;
16514        for (int i = 0; i < childCount; i++) {
16515            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16516            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16517            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16518                    childRes.origUsers, childRes, user, installReason);
16519        }
16520    }
16521
16522    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16523            String installerPackageName, int[] allUsers, int[] installedForUsers,
16524            PackageInstalledInfo res, UserHandle user, int installReason) {
16525        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16526
16527        String pkgName = newPackage.packageName;
16528        synchronized (mPackages) {
16529            //write settings. the installStatus will be incomplete at this stage.
16530            //note that the new package setting would have already been
16531            //added to mPackages. It hasn't been persisted yet.
16532            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16533            // TODO: Remove this write? It's also written at the end of this method
16534            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16535            mSettings.writeLPr();
16536            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16537        }
16538
16539        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16540        synchronized (mPackages) {
16541            updatePermissionsLPw(newPackage.packageName, newPackage,
16542                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16543                            ? UPDATE_PERMISSIONS_ALL : 0));
16544            // For system-bundled packages, we assume that installing an upgraded version
16545            // of the package implies that the user actually wants to run that new code,
16546            // so we enable the package.
16547            PackageSetting ps = mSettings.mPackages.get(pkgName);
16548            final int userId = user.getIdentifier();
16549            if (ps != null) {
16550                if (isSystemApp(newPackage)) {
16551                    if (DEBUG_INSTALL) {
16552                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16553                    }
16554                    // Enable system package for requested users
16555                    if (res.origUsers != null) {
16556                        for (int origUserId : res.origUsers) {
16557                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16558                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16559                                        origUserId, installerPackageName);
16560                            }
16561                        }
16562                    }
16563                    // Also convey the prior install/uninstall state
16564                    if (allUsers != null && installedForUsers != null) {
16565                        for (int currentUserId : allUsers) {
16566                            final boolean installed = ArrayUtils.contains(
16567                                    installedForUsers, currentUserId);
16568                            if (DEBUG_INSTALL) {
16569                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16570                            }
16571                            ps.setInstalled(installed, currentUserId);
16572                        }
16573                        // these install state changes will be persisted in the
16574                        // upcoming call to mSettings.writeLPr().
16575                    }
16576                }
16577                // It's implied that when a user requests installation, they want the app to be
16578                // installed and enabled.
16579                if (userId != UserHandle.USER_ALL) {
16580                    ps.setInstalled(true, userId);
16581                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16582                }
16583
16584                // When replacing an existing package, preserve the original install reason for all
16585                // users that had the package installed before.
16586                final Set<Integer> previousUserIds = new ArraySet<>();
16587                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16588                    final int installReasonCount = res.removedInfo.installReasons.size();
16589                    for (int i = 0; i < installReasonCount; i++) {
16590                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16591                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16592                        ps.setInstallReason(previousInstallReason, previousUserId);
16593                        previousUserIds.add(previousUserId);
16594                    }
16595                }
16596
16597                // Set install reason for users that are having the package newly installed.
16598                if (userId == UserHandle.USER_ALL) {
16599                    for (int currentUserId : sUserManager.getUserIds()) {
16600                        if (!previousUserIds.contains(currentUserId)) {
16601                            ps.setInstallReason(installReason, currentUserId);
16602                        }
16603                    }
16604                } else if (!previousUserIds.contains(userId)) {
16605                    ps.setInstallReason(installReason, userId);
16606                }
16607                mSettings.writeKernelMappingLPr(ps);
16608            }
16609            res.name = pkgName;
16610            res.uid = newPackage.applicationInfo.uid;
16611            res.pkg = newPackage;
16612            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16613            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16614            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16615            //to update install status
16616            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16617            mSettings.writeLPr();
16618            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16619        }
16620
16621        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16622    }
16623
16624    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16625        try {
16626            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16627            installPackageLI(args, res);
16628        } finally {
16629            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16630        }
16631    }
16632
16633    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16634        final int installFlags = args.installFlags;
16635        final String installerPackageName = args.installerPackageName;
16636        final String volumeUuid = args.volumeUuid;
16637        final File tmpPackageFile = new File(args.getCodePath());
16638        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16639        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16640                || (args.volumeUuid != null));
16641        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16642        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16643        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16644        boolean replace = false;
16645        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16646        if (args.move != null) {
16647            // moving a complete application; perform an initial scan on the new install location
16648            scanFlags |= SCAN_INITIAL;
16649        }
16650        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16651            scanFlags |= SCAN_DONT_KILL_APP;
16652        }
16653        if (instantApp) {
16654            scanFlags |= SCAN_AS_INSTANT_APP;
16655        }
16656        if (fullApp) {
16657            scanFlags |= SCAN_AS_FULL_APP;
16658        }
16659
16660        // Result object to be returned
16661        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16662
16663        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16664
16665        // Sanity check
16666        if (instantApp && (forwardLocked || onExternal)) {
16667            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16668                    + " external=" + onExternal);
16669            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16670            return;
16671        }
16672
16673        // Retrieve PackageSettings and parse package
16674        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16675                | PackageParser.PARSE_ENFORCE_CODE
16676                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16677                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16678                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16679                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16680        PackageParser pp = new PackageParser();
16681        pp.setSeparateProcesses(mSeparateProcesses);
16682        pp.setDisplayMetrics(mMetrics);
16683        pp.setCallback(mPackageParserCallback);
16684
16685        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16686        final PackageParser.Package pkg;
16687        try {
16688            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16689        } catch (PackageParserException e) {
16690            res.setError("Failed parse during installPackageLI", e);
16691            return;
16692        } finally {
16693            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16694        }
16695
16696        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16697        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16698            Slog.w(TAG, "Instant app package " + pkg.packageName
16699                    + " does not target O, this will be a fatal error.");
16700            // STOPSHIP: Make this a fatal error
16701            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16702        }
16703        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16704            Slog.w(TAG, "Instant app package " + pkg.packageName
16705                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16706            // STOPSHIP: Make this a fatal error
16707            pkg.applicationInfo.targetSandboxVersion = 2;
16708        }
16709
16710        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16711            // Static shared libraries have synthetic package names
16712            renameStaticSharedLibraryPackage(pkg);
16713
16714            // No static shared libs on external storage
16715            if (onExternal) {
16716                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16717                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16718                        "Packages declaring static-shared libs cannot be updated");
16719                return;
16720            }
16721        }
16722
16723        // If we are installing a clustered package add results for the children
16724        if (pkg.childPackages != null) {
16725            synchronized (mPackages) {
16726                final int childCount = pkg.childPackages.size();
16727                for (int i = 0; i < childCount; i++) {
16728                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16729                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16730                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16731                    childRes.pkg = childPkg;
16732                    childRes.name = childPkg.packageName;
16733                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16734                    if (childPs != null) {
16735                        childRes.origUsers = childPs.queryInstalledUsers(
16736                                sUserManager.getUserIds(), true);
16737                    }
16738                    if ((mPackages.containsKey(childPkg.packageName))) {
16739                        childRes.removedInfo = new PackageRemovedInfo();
16740                        childRes.removedInfo.removedPackage = childPkg.packageName;
16741                    }
16742                    if (res.addedChildPackages == null) {
16743                        res.addedChildPackages = new ArrayMap<>();
16744                    }
16745                    res.addedChildPackages.put(childPkg.packageName, childRes);
16746                }
16747            }
16748        }
16749
16750        // If package doesn't declare API override, mark that we have an install
16751        // time CPU ABI override.
16752        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16753            pkg.cpuAbiOverride = args.abiOverride;
16754        }
16755
16756        String pkgName = res.name = pkg.packageName;
16757        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16758            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16759                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16760                return;
16761            }
16762        }
16763
16764        try {
16765            // either use what we've been given or parse directly from the APK
16766            if (args.certificates != null) {
16767                try {
16768                    PackageParser.populateCertificates(pkg, args.certificates);
16769                } catch (PackageParserException e) {
16770                    // there was something wrong with the certificates we were given;
16771                    // try to pull them from the APK
16772                    PackageParser.collectCertificates(pkg, parseFlags);
16773                }
16774            } else {
16775                PackageParser.collectCertificates(pkg, parseFlags);
16776            }
16777        } catch (PackageParserException e) {
16778            res.setError("Failed collect during installPackageLI", e);
16779            return;
16780        }
16781
16782        // Get rid of all references to package scan path via parser.
16783        pp = null;
16784        String oldCodePath = null;
16785        boolean systemApp = false;
16786        synchronized (mPackages) {
16787            // Check if installing already existing package
16788            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16789                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16790                if (pkg.mOriginalPackages != null
16791                        && pkg.mOriginalPackages.contains(oldName)
16792                        && mPackages.containsKey(oldName)) {
16793                    // This package is derived from an original package,
16794                    // and this device has been updating from that original
16795                    // name.  We must continue using the original name, so
16796                    // rename the new package here.
16797                    pkg.setPackageName(oldName);
16798                    pkgName = pkg.packageName;
16799                    replace = true;
16800                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16801                            + oldName + " pkgName=" + pkgName);
16802                } else if (mPackages.containsKey(pkgName)) {
16803                    // This package, under its official name, already exists
16804                    // on the device; we should replace it.
16805                    replace = true;
16806                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16807                }
16808
16809                // Child packages are installed through the parent package
16810                if (pkg.parentPackage != null) {
16811                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16812                            "Package " + pkg.packageName + " is child of package "
16813                                    + pkg.parentPackage.parentPackage + ". Child packages "
16814                                    + "can be updated only through the parent package.");
16815                    return;
16816                }
16817
16818                if (replace) {
16819                    // Prevent apps opting out from runtime permissions
16820                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16821                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16822                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16823                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16824                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16825                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16826                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16827                                        + " doesn't support runtime permissions but the old"
16828                                        + " target SDK " + oldTargetSdk + " does.");
16829                        return;
16830                    }
16831                    // Prevent apps from downgrading their targetSandbox.
16832                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16833                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16834                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16835                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16836                                "Package " + pkg.packageName + " new target sandbox "
16837                                + newTargetSandbox + " is incompatible with the previous value of"
16838                                + oldTargetSandbox + ".");
16839                        return;
16840                    }
16841
16842                    // Prevent installing of child packages
16843                    if (oldPackage.parentPackage != null) {
16844                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16845                                "Package " + pkg.packageName + " is child of package "
16846                                        + oldPackage.parentPackage + ". Child packages "
16847                                        + "can be updated only through the parent package.");
16848                        return;
16849                    }
16850                }
16851            }
16852
16853            PackageSetting ps = mSettings.mPackages.get(pkgName);
16854            if (ps != null) {
16855                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16856
16857                // Static shared libs have same package with different versions where
16858                // we internally use a synthetic package name to allow multiple versions
16859                // of the same package, therefore we need to compare signatures against
16860                // the package setting for the latest library version.
16861                PackageSetting signatureCheckPs = ps;
16862                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16863                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16864                    if (libraryEntry != null) {
16865                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16866                    }
16867                }
16868
16869                // Quick sanity check that we're signed correctly if updating;
16870                // we'll check this again later when scanning, but we want to
16871                // bail early here before tripping over redefined permissions.
16872                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16873                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16874                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16875                                + pkg.packageName + " upgrade keys do not match the "
16876                                + "previously installed version");
16877                        return;
16878                    }
16879                } else {
16880                    try {
16881                        verifySignaturesLP(signatureCheckPs, pkg);
16882                    } catch (PackageManagerException e) {
16883                        res.setError(e.error, e.getMessage());
16884                        return;
16885                    }
16886                }
16887
16888                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16889                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16890                    systemApp = (ps.pkg.applicationInfo.flags &
16891                            ApplicationInfo.FLAG_SYSTEM) != 0;
16892                }
16893                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16894            }
16895
16896            int N = pkg.permissions.size();
16897            for (int i = N-1; i >= 0; i--) {
16898                PackageParser.Permission perm = pkg.permissions.get(i);
16899                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16900
16901                // Don't allow anyone but the platform to define ephemeral permissions.
16902                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16903                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16904                    Slog.w(TAG, "Package " + pkg.packageName
16905                            + " attempting to delcare ephemeral permission "
16906                            + perm.info.name + "; Removing ephemeral.");
16907                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16908                }
16909                // Check whether the newly-scanned package wants to define an already-defined perm
16910                if (bp != null) {
16911                    // If the defining package is signed with our cert, it's okay.  This
16912                    // also includes the "updating the same package" case, of course.
16913                    // "updating same package" could also involve key-rotation.
16914                    final boolean sigsOk;
16915                    if (bp.sourcePackage.equals(pkg.packageName)
16916                            && (bp.packageSetting instanceof PackageSetting)
16917                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16918                                    scanFlags))) {
16919                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16920                    } else {
16921                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16922                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16923                    }
16924                    if (!sigsOk) {
16925                        // If the owning package is the system itself, we log but allow
16926                        // install to proceed; we fail the install on all other permission
16927                        // redefinitions.
16928                        if (!bp.sourcePackage.equals("android")) {
16929                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16930                                    + pkg.packageName + " attempting to redeclare permission "
16931                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16932                            res.origPermission = perm.info.name;
16933                            res.origPackage = bp.sourcePackage;
16934                            return;
16935                        } else {
16936                            Slog.w(TAG, "Package " + pkg.packageName
16937                                    + " attempting to redeclare system permission "
16938                                    + perm.info.name + "; ignoring new declaration");
16939                            pkg.permissions.remove(i);
16940                        }
16941                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16942                        // Prevent apps to change protection level to dangerous from any other
16943                        // type as this would allow a privilege escalation where an app adds a
16944                        // normal/signature permission in other app's group and later redefines
16945                        // it as dangerous leading to the group auto-grant.
16946                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16947                                == PermissionInfo.PROTECTION_DANGEROUS) {
16948                            if (bp != null && !bp.isRuntime()) {
16949                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16950                                        + "non-runtime permission " + perm.info.name
16951                                        + " to runtime; keeping old protection level");
16952                                perm.info.protectionLevel = bp.protectionLevel;
16953                            }
16954                        }
16955                    }
16956                }
16957            }
16958        }
16959
16960        if (systemApp) {
16961            if (onExternal) {
16962                // Abort update; system app can't be replaced with app on sdcard
16963                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16964                        "Cannot install updates to system apps on sdcard");
16965                return;
16966            } else if (instantApp) {
16967                // Abort update; system app can't be replaced with an instant app
16968                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16969                        "Cannot update a system app with an instant app");
16970                return;
16971            }
16972        }
16973
16974        if (args.move != null) {
16975            // We did an in-place move, so dex is ready to roll
16976            scanFlags |= SCAN_NO_DEX;
16977            scanFlags |= SCAN_MOVE;
16978
16979            synchronized (mPackages) {
16980                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16981                if (ps == null) {
16982                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16983                            "Missing settings for moved package " + pkgName);
16984                }
16985
16986                // We moved the entire application as-is, so bring over the
16987                // previously derived ABI information.
16988                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16989                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16990            }
16991
16992        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16993            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16994            scanFlags |= SCAN_NO_DEX;
16995
16996            try {
16997                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16998                    args.abiOverride : pkg.cpuAbiOverride);
16999                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17000                        true /*extractLibs*/, mAppLib32InstallDir);
17001            } catch (PackageManagerException pme) {
17002                Slog.e(TAG, "Error deriving application ABI", pme);
17003                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17004                return;
17005            }
17006
17007            // Shared libraries for the package need to be updated.
17008            synchronized (mPackages) {
17009                try {
17010                    updateSharedLibrariesLPr(pkg, null);
17011                } catch (PackageManagerException e) {
17012                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17013                }
17014            }
17015
17016            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17017            // Do not run PackageDexOptimizer through the local performDexOpt
17018            // method because `pkg` may not be in `mPackages` yet.
17019            //
17020            // Also, don't fail application installs if the dexopt step fails.
17021            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17022                    null /* instructionSets */, false /* checkProfiles */,
17023                    getCompilerFilterForReason(REASON_INSTALL),
17024                    getOrCreateCompilerPackageStats(pkg),
17025                    mDexManager.isUsedByOtherApps(pkg.packageName));
17026            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17027
17028            // Notify BackgroundDexOptService that the package has been changed.
17029            // If this is an update of a package which used to fail to compile,
17030            // BDOS will remove it from its blacklist.
17031            // TODO: Layering violation
17032            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17033        }
17034
17035        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17036            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17037            return;
17038        }
17039
17040        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17041
17042        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17043                "installPackageLI")) {
17044            if (replace) {
17045                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17046                    // Static libs have a synthetic package name containing the version
17047                    // and cannot be updated as an update would get a new package name,
17048                    // unless this is the exact same version code which is useful for
17049                    // development.
17050                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17051                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17052                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17053                                + "static-shared libs cannot be updated");
17054                        return;
17055                    }
17056                }
17057                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17058                        installerPackageName, res, args.installReason);
17059            } else {
17060                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17061                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17062            }
17063        }
17064
17065        synchronized (mPackages) {
17066            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17067            if (ps != null) {
17068                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17069                ps.setUpdateAvailable(false /*updateAvailable*/);
17070            }
17071
17072            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17073            for (int i = 0; i < childCount; i++) {
17074                PackageParser.Package childPkg = pkg.childPackages.get(i);
17075                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17076                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17077                if (childPs != null) {
17078                    childRes.newUsers = childPs.queryInstalledUsers(
17079                            sUserManager.getUserIds(), true);
17080                }
17081            }
17082
17083            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17084                updateSequenceNumberLP(pkgName, res.newUsers);
17085                updateInstantAppInstallerLocked();
17086            }
17087        }
17088    }
17089
17090    private void startIntentFilterVerifications(int userId, boolean replacing,
17091            PackageParser.Package pkg) {
17092        if (mIntentFilterVerifierComponent == null) {
17093            Slog.w(TAG, "No IntentFilter verification will not be done as "
17094                    + "there is no IntentFilterVerifier available!");
17095            return;
17096        }
17097
17098        final int verifierUid = getPackageUid(
17099                mIntentFilterVerifierComponent.getPackageName(),
17100                MATCH_DEBUG_TRIAGED_MISSING,
17101                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17102
17103        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17104        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17105        mHandler.sendMessage(msg);
17106
17107        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17108        for (int i = 0; i < childCount; i++) {
17109            PackageParser.Package childPkg = pkg.childPackages.get(i);
17110            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17111            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17112            mHandler.sendMessage(msg);
17113        }
17114    }
17115
17116    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17117            PackageParser.Package pkg) {
17118        int size = pkg.activities.size();
17119        if (size == 0) {
17120            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17121                    "No activity, so no need to verify any IntentFilter!");
17122            return;
17123        }
17124
17125        final boolean hasDomainURLs = hasDomainURLs(pkg);
17126        if (!hasDomainURLs) {
17127            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17128                    "No domain URLs, so no need to verify any IntentFilter!");
17129            return;
17130        }
17131
17132        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17133                + " if any IntentFilter from the " + size
17134                + " Activities needs verification ...");
17135
17136        int count = 0;
17137        final String packageName = pkg.packageName;
17138
17139        synchronized (mPackages) {
17140            // If this is a new install and we see that we've already run verification for this
17141            // package, we have nothing to do: it means the state was restored from backup.
17142            if (!replacing) {
17143                IntentFilterVerificationInfo ivi =
17144                        mSettings.getIntentFilterVerificationLPr(packageName);
17145                if (ivi != null) {
17146                    if (DEBUG_DOMAIN_VERIFICATION) {
17147                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17148                                + ivi.getStatusString());
17149                    }
17150                    return;
17151                }
17152            }
17153
17154            // If any filters need to be verified, then all need to be.
17155            boolean needToVerify = false;
17156            for (PackageParser.Activity a : pkg.activities) {
17157                for (ActivityIntentInfo filter : a.intents) {
17158                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17159                        if (DEBUG_DOMAIN_VERIFICATION) {
17160                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17161                        }
17162                        needToVerify = true;
17163                        break;
17164                    }
17165                }
17166            }
17167
17168            if (needToVerify) {
17169                final int verificationId = mIntentFilterVerificationToken++;
17170                for (PackageParser.Activity a : pkg.activities) {
17171                    for (ActivityIntentInfo filter : a.intents) {
17172                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17173                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17174                                    "Verification needed for IntentFilter:" + filter.toString());
17175                            mIntentFilterVerifier.addOneIntentFilterVerification(
17176                                    verifierUid, userId, verificationId, filter, packageName);
17177                            count++;
17178                        }
17179                    }
17180                }
17181            }
17182        }
17183
17184        if (count > 0) {
17185            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17186                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17187                    +  " for userId:" + userId);
17188            mIntentFilterVerifier.startVerifications(userId);
17189        } else {
17190            if (DEBUG_DOMAIN_VERIFICATION) {
17191                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17192            }
17193        }
17194    }
17195
17196    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17197        final ComponentName cn  = filter.activity.getComponentName();
17198        final String packageName = cn.getPackageName();
17199
17200        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17201                packageName);
17202        if (ivi == null) {
17203            return true;
17204        }
17205        int status = ivi.getStatus();
17206        switch (status) {
17207            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17208            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17209                return true;
17210
17211            default:
17212                // Nothing to do
17213                return false;
17214        }
17215    }
17216
17217    private static boolean isMultiArch(ApplicationInfo info) {
17218        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17219    }
17220
17221    private static boolean isExternal(PackageParser.Package pkg) {
17222        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17223    }
17224
17225    private static boolean isExternal(PackageSetting ps) {
17226        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17227    }
17228
17229    private static boolean isSystemApp(PackageParser.Package pkg) {
17230        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17231    }
17232
17233    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17234        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17235    }
17236
17237    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17238        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17239    }
17240
17241    private static boolean isSystemApp(PackageSetting ps) {
17242        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17243    }
17244
17245    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17246        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17247    }
17248
17249    private int packageFlagsToInstallFlags(PackageSetting ps) {
17250        int installFlags = 0;
17251        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17252            // This existing package was an external ASEC install when we have
17253            // the external flag without a UUID
17254            installFlags |= PackageManager.INSTALL_EXTERNAL;
17255        }
17256        if (ps.isForwardLocked()) {
17257            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17258        }
17259        return installFlags;
17260    }
17261
17262    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17263        if (isExternal(pkg)) {
17264            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17265                return StorageManager.UUID_PRIMARY_PHYSICAL;
17266            } else {
17267                return pkg.volumeUuid;
17268            }
17269        } else {
17270            return StorageManager.UUID_PRIVATE_INTERNAL;
17271        }
17272    }
17273
17274    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17275        if (isExternal(pkg)) {
17276            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17277                return mSettings.getExternalVersion();
17278            } else {
17279                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17280            }
17281        } else {
17282            return mSettings.getInternalVersion();
17283        }
17284    }
17285
17286    private void deleteTempPackageFiles() {
17287        final FilenameFilter filter = new FilenameFilter() {
17288            public boolean accept(File dir, String name) {
17289                return name.startsWith("vmdl") && name.endsWith(".tmp");
17290            }
17291        };
17292        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17293            file.delete();
17294        }
17295    }
17296
17297    @Override
17298    public void deletePackageAsUser(String packageName, int versionCode,
17299            IPackageDeleteObserver observer, int userId, int flags) {
17300        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17301                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17302    }
17303
17304    @Override
17305    public void deletePackageVersioned(VersionedPackage versionedPackage,
17306            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17307        mContext.enforceCallingOrSelfPermission(
17308                android.Manifest.permission.DELETE_PACKAGES, null);
17309        Preconditions.checkNotNull(versionedPackage);
17310        Preconditions.checkNotNull(observer);
17311        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17312                PackageManager.VERSION_CODE_HIGHEST,
17313                Integer.MAX_VALUE, "versionCode must be >= -1");
17314
17315        final String packageName = versionedPackage.getPackageName();
17316        // TODO: We will change version code to long, so in the new API it is long
17317        final int versionCode = (int) versionedPackage.getVersionCode();
17318        final String internalPackageName;
17319        synchronized (mPackages) {
17320            // Normalize package name to handle renamed packages and static libs
17321            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17322                    // TODO: We will change version code to long, so in the new API it is long
17323                    (int) versionedPackage.getVersionCode());
17324        }
17325
17326        final int uid = Binder.getCallingUid();
17327        if (!isOrphaned(internalPackageName)
17328                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17329            try {
17330                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17331                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17332                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17333                observer.onUserActionRequired(intent);
17334            } catch (RemoteException re) {
17335            }
17336            return;
17337        }
17338        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17339        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17340        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17341            mContext.enforceCallingOrSelfPermission(
17342                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17343                    "deletePackage for user " + userId);
17344        }
17345
17346        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17347            try {
17348                observer.onPackageDeleted(packageName,
17349                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17350            } catch (RemoteException re) {
17351            }
17352            return;
17353        }
17354
17355        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17356            try {
17357                observer.onPackageDeleted(packageName,
17358                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17359            } catch (RemoteException re) {
17360            }
17361            return;
17362        }
17363
17364        if (DEBUG_REMOVE) {
17365            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17366                    + " deleteAllUsers: " + deleteAllUsers + " version="
17367                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17368                    ? "VERSION_CODE_HIGHEST" : versionCode));
17369        }
17370        // Queue up an async operation since the package deletion may take a little while.
17371        mHandler.post(new Runnable() {
17372            public void run() {
17373                mHandler.removeCallbacks(this);
17374                int returnCode;
17375                if (!deleteAllUsers) {
17376                    returnCode = deletePackageX(internalPackageName, versionCode,
17377                            userId, deleteFlags);
17378                } else {
17379                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17380                            internalPackageName, users);
17381                    // If nobody is blocking uninstall, proceed with delete for all users
17382                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17383                        returnCode = deletePackageX(internalPackageName, versionCode,
17384                                userId, deleteFlags);
17385                    } else {
17386                        // Otherwise uninstall individually for users with blockUninstalls=false
17387                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17388                        for (int userId : users) {
17389                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17390                                returnCode = deletePackageX(internalPackageName, versionCode,
17391                                        userId, userFlags);
17392                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17393                                    Slog.w(TAG, "Package delete failed for user " + userId
17394                                            + ", returnCode " + returnCode);
17395                                }
17396                            }
17397                        }
17398                        // The app has only been marked uninstalled for certain users.
17399                        // We still need to report that delete was blocked
17400                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17401                    }
17402                }
17403                try {
17404                    observer.onPackageDeleted(packageName, returnCode, null);
17405                } catch (RemoteException e) {
17406                    Log.i(TAG, "Observer no longer exists.");
17407                } //end catch
17408            } //end run
17409        });
17410    }
17411
17412    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17413        if (pkg.staticSharedLibName != null) {
17414            return pkg.manifestPackageName;
17415        }
17416        return pkg.packageName;
17417    }
17418
17419    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17420        // Handle renamed packages
17421        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17422        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17423
17424        // Is this a static library?
17425        SparseArray<SharedLibraryEntry> versionedLib =
17426                mStaticLibsByDeclaringPackage.get(packageName);
17427        if (versionedLib == null || versionedLib.size() <= 0) {
17428            return packageName;
17429        }
17430
17431        // Figure out which lib versions the caller can see
17432        SparseIntArray versionsCallerCanSee = null;
17433        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17434        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17435                && callingAppId != Process.ROOT_UID) {
17436            versionsCallerCanSee = new SparseIntArray();
17437            String libName = versionedLib.valueAt(0).info.getName();
17438            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17439            if (uidPackages != null) {
17440                for (String uidPackage : uidPackages) {
17441                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17442                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17443                    if (libIdx >= 0) {
17444                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17445                        versionsCallerCanSee.append(libVersion, libVersion);
17446                    }
17447                }
17448            }
17449        }
17450
17451        // Caller can see nothing - done
17452        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17453            return packageName;
17454        }
17455
17456        // Find the version the caller can see and the app version code
17457        SharedLibraryEntry highestVersion = null;
17458        final int versionCount = versionedLib.size();
17459        for (int i = 0; i < versionCount; i++) {
17460            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17461            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17462                    libEntry.info.getVersion()) < 0) {
17463                continue;
17464            }
17465            // TODO: We will change version code to long, so in the new API it is long
17466            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17467            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17468                if (libVersionCode == versionCode) {
17469                    return libEntry.apk;
17470                }
17471            } else if (highestVersion == null) {
17472                highestVersion = libEntry;
17473            } else if (libVersionCode  > highestVersion.info
17474                    .getDeclaringPackage().getVersionCode()) {
17475                highestVersion = libEntry;
17476            }
17477        }
17478
17479        if (highestVersion != null) {
17480            return highestVersion.apk;
17481        }
17482
17483        return packageName;
17484    }
17485
17486    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17487        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17488              || callingUid == Process.SYSTEM_UID) {
17489            return true;
17490        }
17491        final int callingUserId = UserHandle.getUserId(callingUid);
17492        // If the caller installed the pkgName, then allow it to silently uninstall.
17493        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17494            return true;
17495        }
17496
17497        // Allow package verifier to silently uninstall.
17498        if (mRequiredVerifierPackage != null &&
17499                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17500            return true;
17501        }
17502
17503        // Allow package uninstaller to silently uninstall.
17504        if (mRequiredUninstallerPackage != null &&
17505                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17506            return true;
17507        }
17508
17509        // Allow storage manager to silently uninstall.
17510        if (mStorageManagerPackage != null &&
17511                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17512            return true;
17513        }
17514        return false;
17515    }
17516
17517    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17518        int[] result = EMPTY_INT_ARRAY;
17519        for (int userId : userIds) {
17520            if (getBlockUninstallForUser(packageName, userId)) {
17521                result = ArrayUtils.appendInt(result, userId);
17522            }
17523        }
17524        return result;
17525    }
17526
17527    @Override
17528    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17529        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17530    }
17531
17532    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17533        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17534                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17535        try {
17536            if (dpm != null) {
17537                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17538                        /* callingUserOnly =*/ false);
17539                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17540                        : deviceOwnerComponentName.getPackageName();
17541                // Does the package contains the device owner?
17542                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17543                // this check is probably not needed, since DO should be registered as a device
17544                // admin on some user too. (Original bug for this: b/17657954)
17545                if (packageName.equals(deviceOwnerPackageName)) {
17546                    return true;
17547                }
17548                // Does it contain a device admin for any user?
17549                int[] users;
17550                if (userId == UserHandle.USER_ALL) {
17551                    users = sUserManager.getUserIds();
17552                } else {
17553                    users = new int[]{userId};
17554                }
17555                for (int i = 0; i < users.length; ++i) {
17556                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17557                        return true;
17558                    }
17559                }
17560            }
17561        } catch (RemoteException e) {
17562        }
17563        return false;
17564    }
17565
17566    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17567        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17568    }
17569
17570    /**
17571     *  This method is an internal method that could be get invoked either
17572     *  to delete an installed package or to clean up a failed installation.
17573     *  After deleting an installed package, a broadcast is sent to notify any
17574     *  listeners that the package has been removed. For cleaning up a failed
17575     *  installation, the broadcast is not necessary since the package's
17576     *  installation wouldn't have sent the initial broadcast either
17577     *  The key steps in deleting a package are
17578     *  deleting the package information in internal structures like mPackages,
17579     *  deleting the packages base directories through installd
17580     *  updating mSettings to reflect current status
17581     *  persisting settings for later use
17582     *  sending a broadcast if necessary
17583     */
17584    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17585        final PackageRemovedInfo info = new PackageRemovedInfo();
17586        final boolean res;
17587
17588        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17589                ? UserHandle.USER_ALL : userId;
17590
17591        if (isPackageDeviceAdmin(packageName, removeUser)) {
17592            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17593            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17594        }
17595
17596        PackageSetting uninstalledPs = null;
17597        PackageParser.Package pkg = null;
17598
17599        // for the uninstall-updates case and restricted profiles, remember the per-
17600        // user handle installed state
17601        int[] allUsers;
17602        synchronized (mPackages) {
17603            uninstalledPs = mSettings.mPackages.get(packageName);
17604            if (uninstalledPs == null) {
17605                Slog.w(TAG, "Not removing non-existent package " + packageName);
17606                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17607            }
17608
17609            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17610                    && uninstalledPs.versionCode != versionCode) {
17611                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17612                        + uninstalledPs.versionCode + " != " + versionCode);
17613                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17614            }
17615
17616            // Static shared libs can be declared by any package, so let us not
17617            // allow removing a package if it provides a lib others depend on.
17618            pkg = mPackages.get(packageName);
17619            if (pkg != null && pkg.staticSharedLibName != null) {
17620                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17621                        pkg.staticSharedLibVersion);
17622                if (libEntry != null) {
17623                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17624                            libEntry.info, 0, userId);
17625                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17626                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17627                                + " hosting lib " + libEntry.info.getName() + " version "
17628                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17629                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17630                    }
17631                }
17632            }
17633
17634            allUsers = sUserManager.getUserIds();
17635            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17636        }
17637
17638        final int freezeUser;
17639        if (isUpdatedSystemApp(uninstalledPs)
17640                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17641            // We're downgrading a system app, which will apply to all users, so
17642            // freeze them all during the downgrade
17643            freezeUser = UserHandle.USER_ALL;
17644        } else {
17645            freezeUser = removeUser;
17646        }
17647
17648        synchronized (mInstallLock) {
17649            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17650            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17651                    deleteFlags, "deletePackageX")) {
17652                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17653                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17654            }
17655            synchronized (mPackages) {
17656                if (res) {
17657                    if (pkg != null) {
17658                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17659                    }
17660                    updateSequenceNumberLP(packageName, info.removedUsers);
17661                    updateInstantAppInstallerLocked();
17662                }
17663            }
17664        }
17665
17666        if (res) {
17667            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17668            info.sendPackageRemovedBroadcasts(killApp);
17669            info.sendSystemPackageUpdatedBroadcasts();
17670            info.sendSystemPackageAppearedBroadcasts();
17671        }
17672        // Force a gc here.
17673        Runtime.getRuntime().gc();
17674        // Delete the resources here after sending the broadcast to let
17675        // other processes clean up before deleting resources.
17676        if (info.args != null) {
17677            synchronized (mInstallLock) {
17678                info.args.doPostDeleteLI(true);
17679            }
17680        }
17681
17682        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17683    }
17684
17685    class PackageRemovedInfo {
17686        String removedPackage;
17687        int uid = -1;
17688        int removedAppId = -1;
17689        int[] origUsers;
17690        int[] removedUsers = null;
17691        int[] broadcastUsers = null;
17692        SparseArray<Integer> installReasons;
17693        boolean isRemovedPackageSystemUpdate = false;
17694        boolean isUpdate;
17695        boolean dataRemoved;
17696        boolean removedForAllUsers;
17697        boolean isStaticSharedLib;
17698        // Clean up resources deleted packages.
17699        InstallArgs args = null;
17700        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17701        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17702
17703        void sendPackageRemovedBroadcasts(boolean killApp) {
17704            sendPackageRemovedBroadcastInternal(killApp);
17705            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17706            for (int i = 0; i < childCount; i++) {
17707                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17708                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17709            }
17710        }
17711
17712        void sendSystemPackageUpdatedBroadcasts() {
17713            if (isRemovedPackageSystemUpdate) {
17714                sendSystemPackageUpdatedBroadcastsInternal();
17715                final int childCount = (removedChildPackages != null)
17716                        ? removedChildPackages.size() : 0;
17717                for (int i = 0; i < childCount; i++) {
17718                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17719                    if (childInfo.isRemovedPackageSystemUpdate) {
17720                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17721                    }
17722                }
17723            }
17724        }
17725
17726        void sendSystemPackageAppearedBroadcasts() {
17727            final int packageCount = (appearedChildPackages != null)
17728                    ? appearedChildPackages.size() : 0;
17729            for (int i = 0; i < packageCount; i++) {
17730                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17731                sendPackageAddedForNewUsers(installedInfo.name, true,
17732                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17733            }
17734        }
17735
17736        private void sendSystemPackageUpdatedBroadcastsInternal() {
17737            Bundle extras = new Bundle(2);
17738            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17739            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17740            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17741                    extras, 0, null, null, null);
17742            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17743                    extras, 0, null, null, null);
17744            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17745                    null, 0, removedPackage, null, null);
17746        }
17747
17748        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17749            // Don't send static shared library removal broadcasts as these
17750            // libs are visible only the the apps that depend on them an one
17751            // cannot remove the library if it has a dependency.
17752            if (isStaticSharedLib) {
17753                return;
17754            }
17755            Bundle extras = new Bundle(2);
17756            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17757            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17758            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17759            if (isUpdate || isRemovedPackageSystemUpdate) {
17760                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17761            }
17762            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17763            if (removedPackage != null) {
17764                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17765                        extras, 0, null, null, broadcastUsers);
17766                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17767                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17768                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17769                            null, null, broadcastUsers);
17770                }
17771            }
17772            if (removedAppId >= 0) {
17773                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17774                        broadcastUsers);
17775            }
17776        }
17777    }
17778
17779    /*
17780     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17781     * flag is not set, the data directory is removed as well.
17782     * make sure this flag is set for partially installed apps. If not its meaningless to
17783     * delete a partially installed application.
17784     */
17785    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17786            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17787        String packageName = ps.name;
17788        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17789        // Retrieve object to delete permissions for shared user later on
17790        final PackageParser.Package deletedPkg;
17791        final PackageSetting deletedPs;
17792        // reader
17793        synchronized (mPackages) {
17794            deletedPkg = mPackages.get(packageName);
17795            deletedPs = mSettings.mPackages.get(packageName);
17796            if (outInfo != null) {
17797                outInfo.removedPackage = packageName;
17798                outInfo.isStaticSharedLib = deletedPkg != null
17799                        && deletedPkg.staticSharedLibName != null;
17800                outInfo.removedUsers = deletedPs != null
17801                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17802                        : null;
17803                if (outInfo.removedUsers == null) {
17804                    outInfo.broadcastUsers = null;
17805                } else {
17806                    outInfo.broadcastUsers = EMPTY_INT_ARRAY;
17807                    int[] allUsers = outInfo.removedUsers;
17808                    for (int i = allUsers.length - 1; i >= 0; --i) {
17809                        final int userId = allUsers[i];
17810                        if (deletedPs.getInstantApp(userId)) {
17811                            continue;
17812                        }
17813                        outInfo.broadcastUsers =
17814                                ArrayUtils.appendInt(outInfo.broadcastUsers, userId);
17815                    }
17816                }
17817            }
17818        }
17819
17820        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17821
17822        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17823            final PackageParser.Package resolvedPkg;
17824            if (deletedPkg != null) {
17825                resolvedPkg = deletedPkg;
17826            } else {
17827                // We don't have a parsed package when it lives on an ejected
17828                // adopted storage device, so fake something together
17829                resolvedPkg = new PackageParser.Package(ps.name);
17830                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17831            }
17832            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17833                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17834            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17835            if (outInfo != null) {
17836                outInfo.dataRemoved = true;
17837            }
17838            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17839        }
17840
17841        int removedAppId = -1;
17842
17843        // writer
17844        synchronized (mPackages) {
17845            boolean installedStateChanged = false;
17846            if (deletedPs != null) {
17847                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17848                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17849                    clearDefaultBrowserIfNeeded(packageName);
17850                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17851                    removedAppId = mSettings.removePackageLPw(packageName);
17852                    if (outInfo != null) {
17853                        outInfo.removedAppId = removedAppId;
17854                    }
17855                    updatePermissionsLPw(deletedPs.name, null, 0);
17856                    if (deletedPs.sharedUser != null) {
17857                        // Remove permissions associated with package. Since runtime
17858                        // permissions are per user we have to kill the removed package
17859                        // or packages running under the shared user of the removed
17860                        // package if revoking the permissions requested only by the removed
17861                        // package is successful and this causes a change in gids.
17862                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17863                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17864                                    userId);
17865                            if (userIdToKill == UserHandle.USER_ALL
17866                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17867                                // If gids changed for this user, kill all affected packages.
17868                                mHandler.post(new Runnable() {
17869                                    @Override
17870                                    public void run() {
17871                                        // This has to happen with no lock held.
17872                                        killApplication(deletedPs.name, deletedPs.appId,
17873                                                KILL_APP_REASON_GIDS_CHANGED);
17874                                    }
17875                                });
17876                                break;
17877                            }
17878                        }
17879                    }
17880                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17881                }
17882                // make sure to preserve per-user disabled state if this removal was just
17883                // a downgrade of a system app to the factory package
17884                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17885                    if (DEBUG_REMOVE) {
17886                        Slog.d(TAG, "Propagating install state across downgrade");
17887                    }
17888                    for (int userId : allUserHandles) {
17889                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17890                        if (DEBUG_REMOVE) {
17891                            Slog.d(TAG, "    user " + userId + " => " + installed);
17892                        }
17893                        if (installed != ps.getInstalled(userId)) {
17894                            installedStateChanged = true;
17895                        }
17896                        ps.setInstalled(installed, userId);
17897                    }
17898                }
17899            }
17900            // can downgrade to reader
17901            if (writeSettings) {
17902                // Save settings now
17903                mSettings.writeLPr();
17904            }
17905            if (installedStateChanged) {
17906                mSettings.writeKernelMappingLPr(ps);
17907            }
17908        }
17909        if (removedAppId != -1) {
17910            // A user ID was deleted here. Go through all users and remove it
17911            // from KeyStore.
17912            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17913        }
17914    }
17915
17916    static boolean locationIsPrivileged(File path) {
17917        try {
17918            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17919                    .getCanonicalPath();
17920            return path.getCanonicalPath().startsWith(privilegedAppDir);
17921        } catch (IOException e) {
17922            Slog.e(TAG, "Unable to access code path " + path);
17923        }
17924        return false;
17925    }
17926
17927    /*
17928     * Tries to delete system package.
17929     */
17930    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17931            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17932            boolean writeSettings) {
17933        if (deletedPs.parentPackageName != null) {
17934            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17935            return false;
17936        }
17937
17938        final boolean applyUserRestrictions
17939                = (allUserHandles != null) && (outInfo.origUsers != null);
17940        final PackageSetting disabledPs;
17941        // Confirm if the system package has been updated
17942        // An updated system app can be deleted. This will also have to restore
17943        // the system pkg from system partition
17944        // reader
17945        synchronized (mPackages) {
17946            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17947        }
17948
17949        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17950                + " disabledPs=" + disabledPs);
17951
17952        if (disabledPs == null) {
17953            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17954            return false;
17955        } else if (DEBUG_REMOVE) {
17956            Slog.d(TAG, "Deleting system pkg from data partition");
17957        }
17958
17959        if (DEBUG_REMOVE) {
17960            if (applyUserRestrictions) {
17961                Slog.d(TAG, "Remembering install states:");
17962                for (int userId : allUserHandles) {
17963                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17964                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17965                }
17966            }
17967        }
17968
17969        // Delete the updated package
17970        outInfo.isRemovedPackageSystemUpdate = true;
17971        if (outInfo.removedChildPackages != null) {
17972            final int childCount = (deletedPs.childPackageNames != null)
17973                    ? deletedPs.childPackageNames.size() : 0;
17974            for (int i = 0; i < childCount; i++) {
17975                String childPackageName = deletedPs.childPackageNames.get(i);
17976                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17977                        .contains(childPackageName)) {
17978                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17979                            childPackageName);
17980                    if (childInfo != null) {
17981                        childInfo.isRemovedPackageSystemUpdate = true;
17982                    }
17983                }
17984            }
17985        }
17986
17987        if (disabledPs.versionCode < deletedPs.versionCode) {
17988            // Delete data for downgrades
17989            flags &= ~PackageManager.DELETE_KEEP_DATA;
17990        } else {
17991            // Preserve data by setting flag
17992            flags |= PackageManager.DELETE_KEEP_DATA;
17993        }
17994
17995        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17996                outInfo, writeSettings, disabledPs.pkg);
17997        if (!ret) {
17998            return false;
17999        }
18000
18001        // writer
18002        synchronized (mPackages) {
18003            // Reinstate the old system package
18004            enableSystemPackageLPw(disabledPs.pkg);
18005            // Remove any native libraries from the upgraded package.
18006            removeNativeBinariesLI(deletedPs);
18007        }
18008
18009        // Install the system package
18010        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18011        int parseFlags = mDefParseFlags
18012                | PackageParser.PARSE_MUST_BE_APK
18013                | PackageParser.PARSE_IS_SYSTEM
18014                | PackageParser.PARSE_IS_SYSTEM_DIR;
18015        if (locationIsPrivileged(disabledPs.codePath)) {
18016            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18017        }
18018
18019        final PackageParser.Package newPkg;
18020        try {
18021            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18022                0 /* currentTime */, null);
18023        } catch (PackageManagerException e) {
18024            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18025                    + e.getMessage());
18026            return false;
18027        }
18028
18029        try {
18030            // update shared libraries for the newly re-installed system package
18031            updateSharedLibrariesLPr(newPkg, null);
18032        } catch (PackageManagerException e) {
18033            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18034        }
18035
18036        prepareAppDataAfterInstallLIF(newPkg);
18037
18038        // writer
18039        synchronized (mPackages) {
18040            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18041
18042            // Propagate the permissions state as we do not want to drop on the floor
18043            // runtime permissions. The update permissions method below will take
18044            // care of removing obsolete permissions and grant install permissions.
18045            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18046            updatePermissionsLPw(newPkg.packageName, newPkg,
18047                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18048
18049            if (applyUserRestrictions) {
18050                boolean installedStateChanged = false;
18051                if (DEBUG_REMOVE) {
18052                    Slog.d(TAG, "Propagating install state across reinstall");
18053                }
18054                for (int userId : allUserHandles) {
18055                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18056                    if (DEBUG_REMOVE) {
18057                        Slog.d(TAG, "    user " + userId + " => " + installed);
18058                    }
18059                    if (installed != ps.getInstalled(userId)) {
18060                        installedStateChanged = true;
18061                    }
18062                    ps.setInstalled(installed, userId);
18063
18064                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18065                }
18066                // Regardless of writeSettings we need to ensure that this restriction
18067                // state propagation is persisted
18068                mSettings.writeAllUsersPackageRestrictionsLPr();
18069                if (installedStateChanged) {
18070                    mSettings.writeKernelMappingLPr(ps);
18071                }
18072            }
18073            // can downgrade to reader here
18074            if (writeSettings) {
18075                mSettings.writeLPr();
18076            }
18077        }
18078        return true;
18079    }
18080
18081    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18082            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18083            PackageRemovedInfo outInfo, boolean writeSettings,
18084            PackageParser.Package replacingPackage) {
18085        synchronized (mPackages) {
18086            if (outInfo != null) {
18087                outInfo.uid = ps.appId;
18088            }
18089
18090            if (outInfo != null && outInfo.removedChildPackages != null) {
18091                final int childCount = (ps.childPackageNames != null)
18092                        ? ps.childPackageNames.size() : 0;
18093                for (int i = 0; i < childCount; i++) {
18094                    String childPackageName = ps.childPackageNames.get(i);
18095                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18096                    if (childPs == null) {
18097                        return false;
18098                    }
18099                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18100                            childPackageName);
18101                    if (childInfo != null) {
18102                        childInfo.uid = childPs.appId;
18103                    }
18104                }
18105            }
18106        }
18107
18108        // Delete package data from internal structures and also remove data if flag is set
18109        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18110
18111        // Delete the child packages data
18112        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18113        for (int i = 0; i < childCount; i++) {
18114            PackageSetting childPs;
18115            synchronized (mPackages) {
18116                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18117            }
18118            if (childPs != null) {
18119                PackageRemovedInfo childOutInfo = (outInfo != null
18120                        && outInfo.removedChildPackages != null)
18121                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18122                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18123                        && (replacingPackage != null
18124                        && !replacingPackage.hasChildPackage(childPs.name))
18125                        ? flags & ~DELETE_KEEP_DATA : flags;
18126                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18127                        deleteFlags, writeSettings);
18128            }
18129        }
18130
18131        // Delete application code and resources only for parent packages
18132        if (ps.parentPackageName == null) {
18133            if (deleteCodeAndResources && (outInfo != null)) {
18134                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18135                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18136                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18137            }
18138        }
18139
18140        return true;
18141    }
18142
18143    @Override
18144    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18145            int userId) {
18146        mContext.enforceCallingOrSelfPermission(
18147                android.Manifest.permission.DELETE_PACKAGES, null);
18148        synchronized (mPackages) {
18149            PackageSetting ps = mSettings.mPackages.get(packageName);
18150            if (ps == null) {
18151                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18152                return false;
18153            }
18154            // Cannot block uninstall of static shared libs as they are
18155            // considered a part of the using app (emulating static linking).
18156            // Also static libs are installed always on internal storage.
18157            PackageParser.Package pkg = mPackages.get(packageName);
18158            if (pkg != null && pkg.staticSharedLibName != null) {
18159                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18160                        + " providing static shared library: " + pkg.staticSharedLibName);
18161                return false;
18162            }
18163            if (!ps.getInstalled(userId)) {
18164                // Can't block uninstall for an app that is not installed or enabled.
18165                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18166                return false;
18167            }
18168            ps.setBlockUninstall(blockUninstall, userId);
18169            mSettings.writePackageRestrictionsLPr(userId);
18170        }
18171        return true;
18172    }
18173
18174    @Override
18175    public boolean getBlockUninstallForUser(String packageName, int userId) {
18176        synchronized (mPackages) {
18177            PackageSetting ps = mSettings.mPackages.get(packageName);
18178            if (ps == null) {
18179                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18180                return false;
18181            }
18182            return ps.getBlockUninstall(userId);
18183        }
18184    }
18185
18186    @Override
18187    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18188        int callingUid = Binder.getCallingUid();
18189        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18190            throw new SecurityException(
18191                    "setRequiredForSystemUser can only be run by the system or root");
18192        }
18193        synchronized (mPackages) {
18194            PackageSetting ps = mSettings.mPackages.get(packageName);
18195            if (ps == null) {
18196                Log.w(TAG, "Package doesn't exist: " + packageName);
18197                return false;
18198            }
18199            if (systemUserApp) {
18200                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18201            } else {
18202                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18203            }
18204            mSettings.writeLPr();
18205        }
18206        return true;
18207    }
18208
18209    /*
18210     * This method handles package deletion in general
18211     */
18212    private boolean deletePackageLIF(String packageName, UserHandle user,
18213            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18214            PackageRemovedInfo outInfo, boolean writeSettings,
18215            PackageParser.Package replacingPackage) {
18216        if (packageName == null) {
18217            Slog.w(TAG, "Attempt to delete null packageName.");
18218            return false;
18219        }
18220
18221        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18222
18223        PackageSetting ps;
18224        synchronized (mPackages) {
18225            ps = mSettings.mPackages.get(packageName);
18226            if (ps == null) {
18227                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18228                return false;
18229            }
18230
18231            if (ps.parentPackageName != null && (!isSystemApp(ps)
18232                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18233                if (DEBUG_REMOVE) {
18234                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18235                            + ((user == null) ? UserHandle.USER_ALL : user));
18236                }
18237                final int removedUserId = (user != null) ? user.getIdentifier()
18238                        : UserHandle.USER_ALL;
18239                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18240                    return false;
18241                }
18242                markPackageUninstalledForUserLPw(ps, user);
18243                scheduleWritePackageRestrictionsLocked(user);
18244                return true;
18245            }
18246        }
18247
18248        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18249                && user.getIdentifier() != UserHandle.USER_ALL)) {
18250            // The caller is asking that the package only be deleted for a single
18251            // user.  To do this, we just mark its uninstalled state and delete
18252            // its data. If this is a system app, we only allow this to happen if
18253            // they have set the special DELETE_SYSTEM_APP which requests different
18254            // semantics than normal for uninstalling system apps.
18255            markPackageUninstalledForUserLPw(ps, user);
18256
18257            if (!isSystemApp(ps)) {
18258                // Do not uninstall the APK if an app should be cached
18259                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18260                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18261                    // Other user still have this package installed, so all
18262                    // we need to do is clear this user's data and save that
18263                    // it is uninstalled.
18264                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18265                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18266                        return false;
18267                    }
18268                    scheduleWritePackageRestrictionsLocked(user);
18269                    return true;
18270                } else {
18271                    // We need to set it back to 'installed' so the uninstall
18272                    // broadcasts will be sent correctly.
18273                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18274                    ps.setInstalled(true, user.getIdentifier());
18275                    mSettings.writeKernelMappingLPr(ps);
18276                }
18277            } else {
18278                // This is a system app, so we assume that the
18279                // other users still have this package installed, so all
18280                // we need to do is clear this user's data and save that
18281                // it is uninstalled.
18282                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18283                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18284                    return false;
18285                }
18286                scheduleWritePackageRestrictionsLocked(user);
18287                return true;
18288            }
18289        }
18290
18291        // If we are deleting a composite package for all users, keep track
18292        // of result for each child.
18293        if (ps.childPackageNames != null && outInfo != null) {
18294            synchronized (mPackages) {
18295                final int childCount = ps.childPackageNames.size();
18296                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18297                for (int i = 0; i < childCount; i++) {
18298                    String childPackageName = ps.childPackageNames.get(i);
18299                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18300                    childInfo.removedPackage = childPackageName;
18301                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18302                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18303                    if (childPs != null) {
18304                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18305                    }
18306                }
18307            }
18308        }
18309
18310        boolean ret = false;
18311        if (isSystemApp(ps)) {
18312            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18313            // When an updated system application is deleted we delete the existing resources
18314            // as well and fall back to existing code in system partition
18315            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18316        } else {
18317            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18318            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18319                    outInfo, writeSettings, replacingPackage);
18320        }
18321
18322        // Take a note whether we deleted the package for all users
18323        if (outInfo != null) {
18324            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18325            if (outInfo.removedChildPackages != null) {
18326                synchronized (mPackages) {
18327                    final int childCount = outInfo.removedChildPackages.size();
18328                    for (int i = 0; i < childCount; i++) {
18329                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18330                        if (childInfo != null) {
18331                            childInfo.removedForAllUsers = mPackages.get(
18332                                    childInfo.removedPackage) == null;
18333                        }
18334                    }
18335                }
18336            }
18337            // If we uninstalled an update to a system app there may be some
18338            // child packages that appeared as they are declared in the system
18339            // app but were not declared in the update.
18340            if (isSystemApp(ps)) {
18341                synchronized (mPackages) {
18342                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18343                    final int childCount = (updatedPs.childPackageNames != null)
18344                            ? updatedPs.childPackageNames.size() : 0;
18345                    for (int i = 0; i < childCount; i++) {
18346                        String childPackageName = updatedPs.childPackageNames.get(i);
18347                        if (outInfo.removedChildPackages == null
18348                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18349                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18350                            if (childPs == null) {
18351                                continue;
18352                            }
18353                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18354                            installRes.name = childPackageName;
18355                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18356                            installRes.pkg = mPackages.get(childPackageName);
18357                            installRes.uid = childPs.pkg.applicationInfo.uid;
18358                            if (outInfo.appearedChildPackages == null) {
18359                                outInfo.appearedChildPackages = new ArrayMap<>();
18360                            }
18361                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18362                        }
18363                    }
18364                }
18365            }
18366        }
18367
18368        return ret;
18369    }
18370
18371    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18372        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18373                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18374        for (int nextUserId : userIds) {
18375            if (DEBUG_REMOVE) {
18376                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18377            }
18378            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18379                    false /*installed*/,
18380                    true /*stopped*/,
18381                    true /*notLaunched*/,
18382                    false /*hidden*/,
18383                    false /*suspended*/,
18384                    false /*instantApp*/,
18385                    null /*lastDisableAppCaller*/,
18386                    null /*enabledComponents*/,
18387                    null /*disabledComponents*/,
18388                    false /*blockUninstall*/,
18389                    ps.readUserState(nextUserId).domainVerificationStatus,
18390                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18391        }
18392        mSettings.writeKernelMappingLPr(ps);
18393    }
18394
18395    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18396            PackageRemovedInfo outInfo) {
18397        final PackageParser.Package pkg;
18398        synchronized (mPackages) {
18399            pkg = mPackages.get(ps.name);
18400        }
18401
18402        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18403                : new int[] {userId};
18404        for (int nextUserId : userIds) {
18405            if (DEBUG_REMOVE) {
18406                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18407                        + nextUserId);
18408            }
18409
18410            destroyAppDataLIF(pkg, userId,
18411                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18412            destroyAppProfilesLIF(pkg, userId);
18413            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18414            schedulePackageCleaning(ps.name, nextUserId, false);
18415            synchronized (mPackages) {
18416                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18417                    scheduleWritePackageRestrictionsLocked(nextUserId);
18418                }
18419                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18420            }
18421        }
18422
18423        if (outInfo != null) {
18424            outInfo.removedPackage = ps.name;
18425            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18426            outInfo.removedAppId = ps.appId;
18427            outInfo.removedUsers = userIds;
18428        }
18429
18430        return true;
18431    }
18432
18433    private final class ClearStorageConnection implements ServiceConnection {
18434        IMediaContainerService mContainerService;
18435
18436        @Override
18437        public void onServiceConnected(ComponentName name, IBinder service) {
18438            synchronized (this) {
18439                mContainerService = IMediaContainerService.Stub
18440                        .asInterface(Binder.allowBlocking(service));
18441                notifyAll();
18442            }
18443        }
18444
18445        @Override
18446        public void onServiceDisconnected(ComponentName name) {
18447        }
18448    }
18449
18450    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18451        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18452
18453        final boolean mounted;
18454        if (Environment.isExternalStorageEmulated()) {
18455            mounted = true;
18456        } else {
18457            final String status = Environment.getExternalStorageState();
18458
18459            mounted = status.equals(Environment.MEDIA_MOUNTED)
18460                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18461        }
18462
18463        if (!mounted) {
18464            return;
18465        }
18466
18467        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18468        int[] users;
18469        if (userId == UserHandle.USER_ALL) {
18470            users = sUserManager.getUserIds();
18471        } else {
18472            users = new int[] { userId };
18473        }
18474        final ClearStorageConnection conn = new ClearStorageConnection();
18475        if (mContext.bindServiceAsUser(
18476                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18477            try {
18478                for (int curUser : users) {
18479                    long timeout = SystemClock.uptimeMillis() + 5000;
18480                    synchronized (conn) {
18481                        long now;
18482                        while (conn.mContainerService == null &&
18483                                (now = SystemClock.uptimeMillis()) < timeout) {
18484                            try {
18485                                conn.wait(timeout - now);
18486                            } catch (InterruptedException e) {
18487                            }
18488                        }
18489                    }
18490                    if (conn.mContainerService == null) {
18491                        return;
18492                    }
18493
18494                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18495                    clearDirectory(conn.mContainerService,
18496                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18497                    if (allData) {
18498                        clearDirectory(conn.mContainerService,
18499                                userEnv.buildExternalStorageAppDataDirs(packageName));
18500                        clearDirectory(conn.mContainerService,
18501                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18502                    }
18503                }
18504            } finally {
18505                mContext.unbindService(conn);
18506            }
18507        }
18508    }
18509
18510    @Override
18511    public void clearApplicationProfileData(String packageName) {
18512        enforceSystemOrRoot("Only the system can clear all profile data");
18513
18514        final PackageParser.Package pkg;
18515        synchronized (mPackages) {
18516            pkg = mPackages.get(packageName);
18517        }
18518
18519        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18520            synchronized (mInstallLock) {
18521                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18522            }
18523        }
18524    }
18525
18526    @Override
18527    public void clearApplicationUserData(final String packageName,
18528            final IPackageDataObserver observer, final int userId) {
18529        mContext.enforceCallingOrSelfPermission(
18530                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18531
18532        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18533                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18534
18535        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18536            throw new SecurityException("Cannot clear data for a protected package: "
18537                    + packageName);
18538        }
18539        // Queue up an async operation since the package deletion may take a little while.
18540        mHandler.post(new Runnable() {
18541            public void run() {
18542                mHandler.removeCallbacks(this);
18543                final boolean succeeded;
18544                try (PackageFreezer freezer = freezePackage(packageName,
18545                        "clearApplicationUserData")) {
18546                    synchronized (mInstallLock) {
18547                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18548                    }
18549                    clearExternalStorageDataSync(packageName, userId, true);
18550                    synchronized (mPackages) {
18551                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18552                                packageName, userId);
18553                    }
18554                }
18555                if (succeeded) {
18556                    // invoke DeviceStorageMonitor's update method to clear any notifications
18557                    DeviceStorageMonitorInternal dsm = LocalServices
18558                            .getService(DeviceStorageMonitorInternal.class);
18559                    if (dsm != null) {
18560                        dsm.checkMemory();
18561                    }
18562                }
18563                if(observer != null) {
18564                    try {
18565                        observer.onRemoveCompleted(packageName, succeeded);
18566                    } catch (RemoteException e) {
18567                        Log.i(TAG, "Observer no longer exists.");
18568                    }
18569                } //end if observer
18570            } //end run
18571        });
18572    }
18573
18574    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18575        if (packageName == null) {
18576            Slog.w(TAG, "Attempt to delete null packageName.");
18577            return false;
18578        }
18579
18580        // Try finding details about the requested package
18581        PackageParser.Package pkg;
18582        synchronized (mPackages) {
18583            pkg = mPackages.get(packageName);
18584            if (pkg == null) {
18585                final PackageSetting ps = mSettings.mPackages.get(packageName);
18586                if (ps != null) {
18587                    pkg = ps.pkg;
18588                }
18589            }
18590
18591            if (pkg == null) {
18592                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18593                return false;
18594            }
18595
18596            PackageSetting ps = (PackageSetting) pkg.mExtras;
18597            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18598        }
18599
18600        clearAppDataLIF(pkg, userId,
18601                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18602
18603        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18604        removeKeystoreDataIfNeeded(userId, appId);
18605
18606        UserManagerInternal umInternal = getUserManagerInternal();
18607        final int flags;
18608        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18609            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18610        } else if (umInternal.isUserRunning(userId)) {
18611            flags = StorageManager.FLAG_STORAGE_DE;
18612        } else {
18613            flags = 0;
18614        }
18615        prepareAppDataContentsLIF(pkg, userId, flags);
18616
18617        return true;
18618    }
18619
18620    /**
18621     * Reverts user permission state changes (permissions and flags) in
18622     * all packages for a given user.
18623     *
18624     * @param userId The device user for which to do a reset.
18625     */
18626    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18627        final int packageCount = mPackages.size();
18628        for (int i = 0; i < packageCount; i++) {
18629            PackageParser.Package pkg = mPackages.valueAt(i);
18630            PackageSetting ps = (PackageSetting) pkg.mExtras;
18631            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18632        }
18633    }
18634
18635    private void resetNetworkPolicies(int userId) {
18636        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18637    }
18638
18639    /**
18640     * Reverts user permission state changes (permissions and flags).
18641     *
18642     * @param ps The package for which to reset.
18643     * @param userId The device user for which to do a reset.
18644     */
18645    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18646            final PackageSetting ps, final int userId) {
18647        if (ps.pkg == null) {
18648            return;
18649        }
18650
18651        // These are flags that can change base on user actions.
18652        final int userSettableMask = FLAG_PERMISSION_USER_SET
18653                | FLAG_PERMISSION_USER_FIXED
18654                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18655                | FLAG_PERMISSION_REVIEW_REQUIRED;
18656
18657        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18658                | FLAG_PERMISSION_POLICY_FIXED;
18659
18660        boolean writeInstallPermissions = false;
18661        boolean writeRuntimePermissions = false;
18662
18663        final int permissionCount = ps.pkg.requestedPermissions.size();
18664        for (int i = 0; i < permissionCount; i++) {
18665            String permission = ps.pkg.requestedPermissions.get(i);
18666
18667            BasePermission bp = mSettings.mPermissions.get(permission);
18668            if (bp == null) {
18669                continue;
18670            }
18671
18672            // If shared user we just reset the state to which only this app contributed.
18673            if (ps.sharedUser != null) {
18674                boolean used = false;
18675                final int packageCount = ps.sharedUser.packages.size();
18676                for (int j = 0; j < packageCount; j++) {
18677                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18678                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18679                            && pkg.pkg.requestedPermissions.contains(permission)) {
18680                        used = true;
18681                        break;
18682                    }
18683                }
18684                if (used) {
18685                    continue;
18686                }
18687            }
18688
18689            PermissionsState permissionsState = ps.getPermissionsState();
18690
18691            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18692
18693            // Always clear the user settable flags.
18694            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18695                    bp.name) != null;
18696            // If permission review is enabled and this is a legacy app, mark the
18697            // permission as requiring a review as this is the initial state.
18698            int flags = 0;
18699            if (mPermissionReviewRequired
18700                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18701                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18702            }
18703            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18704                if (hasInstallState) {
18705                    writeInstallPermissions = true;
18706                } else {
18707                    writeRuntimePermissions = true;
18708                }
18709            }
18710
18711            // Below is only runtime permission handling.
18712            if (!bp.isRuntime()) {
18713                continue;
18714            }
18715
18716            // Never clobber system or policy.
18717            if ((oldFlags & policyOrSystemFlags) != 0) {
18718                continue;
18719            }
18720
18721            // If this permission was granted by default, make sure it is.
18722            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18723                if (permissionsState.grantRuntimePermission(bp, userId)
18724                        != PERMISSION_OPERATION_FAILURE) {
18725                    writeRuntimePermissions = true;
18726                }
18727            // If permission review is enabled the permissions for a legacy apps
18728            // are represented as constantly granted runtime ones, so don't revoke.
18729            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18730                // Otherwise, reset the permission.
18731                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18732                switch (revokeResult) {
18733                    case PERMISSION_OPERATION_SUCCESS:
18734                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18735                        writeRuntimePermissions = true;
18736                        final int appId = ps.appId;
18737                        mHandler.post(new Runnable() {
18738                            @Override
18739                            public void run() {
18740                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18741                            }
18742                        });
18743                    } break;
18744                }
18745            }
18746        }
18747
18748        // Synchronously write as we are taking permissions away.
18749        if (writeRuntimePermissions) {
18750            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18751        }
18752
18753        // Synchronously write as we are taking permissions away.
18754        if (writeInstallPermissions) {
18755            mSettings.writeLPr();
18756        }
18757    }
18758
18759    /**
18760     * Remove entries from the keystore daemon. Will only remove it if the
18761     * {@code appId} is valid.
18762     */
18763    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18764        if (appId < 0) {
18765            return;
18766        }
18767
18768        final KeyStore keyStore = KeyStore.getInstance();
18769        if (keyStore != null) {
18770            if (userId == UserHandle.USER_ALL) {
18771                for (final int individual : sUserManager.getUserIds()) {
18772                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18773                }
18774            } else {
18775                keyStore.clearUid(UserHandle.getUid(userId, appId));
18776            }
18777        } else {
18778            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18779        }
18780    }
18781
18782    @Override
18783    public void deleteApplicationCacheFiles(final String packageName,
18784            final IPackageDataObserver observer) {
18785        final int userId = UserHandle.getCallingUserId();
18786        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18787    }
18788
18789    @Override
18790    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18791            final IPackageDataObserver observer) {
18792        mContext.enforceCallingOrSelfPermission(
18793                android.Manifest.permission.DELETE_CACHE_FILES, null);
18794        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18795                /* requireFullPermission= */ true, /* checkShell= */ false,
18796                "delete application cache files");
18797
18798        final PackageParser.Package pkg;
18799        synchronized (mPackages) {
18800            pkg = mPackages.get(packageName);
18801        }
18802
18803        // Queue up an async operation since the package deletion may take a little while.
18804        mHandler.post(new Runnable() {
18805            public void run() {
18806                synchronized (mInstallLock) {
18807                    final int flags = StorageManager.FLAG_STORAGE_DE
18808                            | StorageManager.FLAG_STORAGE_CE;
18809                    // We're only clearing cache files, so we don't care if the
18810                    // app is unfrozen and still able to run
18811                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18812                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18813                }
18814                clearExternalStorageDataSync(packageName, userId, false);
18815                if (observer != null) {
18816                    try {
18817                        observer.onRemoveCompleted(packageName, true);
18818                    } catch (RemoteException e) {
18819                        Log.i(TAG, "Observer no longer exists.");
18820                    }
18821                }
18822            }
18823        });
18824    }
18825
18826    @Override
18827    public void getPackageSizeInfo(final String packageName, int userHandle,
18828            final IPackageStatsObserver observer) {
18829        throw new UnsupportedOperationException(
18830                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18831    }
18832
18833    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18834        final PackageSetting ps;
18835        synchronized (mPackages) {
18836            ps = mSettings.mPackages.get(packageName);
18837            if (ps == null) {
18838                Slog.w(TAG, "Failed to find settings for " + packageName);
18839                return false;
18840            }
18841        }
18842
18843        final String[] packageNames = { packageName };
18844        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18845        final String[] codePaths = { ps.codePathString };
18846
18847        try {
18848            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18849                    ps.appId, ceDataInodes, codePaths, stats);
18850
18851            // For now, ignore code size of packages on system partition
18852            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18853                stats.codeSize = 0;
18854            }
18855
18856            // External clients expect these to be tracked separately
18857            stats.dataSize -= stats.cacheSize;
18858
18859        } catch (InstallerException e) {
18860            Slog.w(TAG, String.valueOf(e));
18861            return false;
18862        }
18863
18864        return true;
18865    }
18866
18867    private int getUidTargetSdkVersionLockedLPr(int uid) {
18868        Object obj = mSettings.getUserIdLPr(uid);
18869        if (obj instanceof SharedUserSetting) {
18870            final SharedUserSetting sus = (SharedUserSetting) obj;
18871            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18872            final Iterator<PackageSetting> it = sus.packages.iterator();
18873            while (it.hasNext()) {
18874                final PackageSetting ps = it.next();
18875                if (ps.pkg != null) {
18876                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18877                    if (v < vers) vers = v;
18878                }
18879            }
18880            return vers;
18881        } else if (obj instanceof PackageSetting) {
18882            final PackageSetting ps = (PackageSetting) obj;
18883            if (ps.pkg != null) {
18884                return ps.pkg.applicationInfo.targetSdkVersion;
18885            }
18886        }
18887        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18888    }
18889
18890    @Override
18891    public void addPreferredActivity(IntentFilter filter, int match,
18892            ComponentName[] set, ComponentName activity, int userId) {
18893        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18894                "Adding preferred");
18895    }
18896
18897    private void addPreferredActivityInternal(IntentFilter filter, int match,
18898            ComponentName[] set, ComponentName activity, boolean always, int userId,
18899            String opname) {
18900        // writer
18901        int callingUid = Binder.getCallingUid();
18902        enforceCrossUserPermission(callingUid, userId,
18903                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18904        if (filter.countActions() == 0) {
18905            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18906            return;
18907        }
18908        synchronized (mPackages) {
18909            if (mContext.checkCallingOrSelfPermission(
18910                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18911                    != PackageManager.PERMISSION_GRANTED) {
18912                if (getUidTargetSdkVersionLockedLPr(callingUid)
18913                        < Build.VERSION_CODES.FROYO) {
18914                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18915                            + callingUid);
18916                    return;
18917                }
18918                mContext.enforceCallingOrSelfPermission(
18919                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18920            }
18921
18922            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18923            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18924                    + userId + ":");
18925            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18926            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18927            scheduleWritePackageRestrictionsLocked(userId);
18928            postPreferredActivityChangedBroadcast(userId);
18929        }
18930    }
18931
18932    private void postPreferredActivityChangedBroadcast(int userId) {
18933        mHandler.post(() -> {
18934            final IActivityManager am = ActivityManager.getService();
18935            if (am == null) {
18936                return;
18937            }
18938
18939            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18940            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18941            try {
18942                am.broadcastIntent(null, intent, null, null,
18943                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18944                        null, false, false, userId);
18945            } catch (RemoteException e) {
18946            }
18947        });
18948    }
18949
18950    @Override
18951    public void replacePreferredActivity(IntentFilter filter, int match,
18952            ComponentName[] set, ComponentName activity, int userId) {
18953        if (filter.countActions() != 1) {
18954            throw new IllegalArgumentException(
18955                    "replacePreferredActivity expects filter to have only 1 action.");
18956        }
18957        if (filter.countDataAuthorities() != 0
18958                || filter.countDataPaths() != 0
18959                || filter.countDataSchemes() > 1
18960                || filter.countDataTypes() != 0) {
18961            throw new IllegalArgumentException(
18962                    "replacePreferredActivity expects filter to have no data authorities, " +
18963                    "paths, or types; and at most one scheme.");
18964        }
18965
18966        final int callingUid = Binder.getCallingUid();
18967        enforceCrossUserPermission(callingUid, userId,
18968                true /* requireFullPermission */, false /* checkShell */,
18969                "replace preferred activity");
18970        synchronized (mPackages) {
18971            if (mContext.checkCallingOrSelfPermission(
18972                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18973                    != PackageManager.PERMISSION_GRANTED) {
18974                if (getUidTargetSdkVersionLockedLPr(callingUid)
18975                        < Build.VERSION_CODES.FROYO) {
18976                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18977                            + Binder.getCallingUid());
18978                    return;
18979                }
18980                mContext.enforceCallingOrSelfPermission(
18981                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18982            }
18983
18984            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18985            if (pir != null) {
18986                // Get all of the existing entries that exactly match this filter.
18987                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18988                if (existing != null && existing.size() == 1) {
18989                    PreferredActivity cur = existing.get(0);
18990                    if (DEBUG_PREFERRED) {
18991                        Slog.i(TAG, "Checking replace of preferred:");
18992                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18993                        if (!cur.mPref.mAlways) {
18994                            Slog.i(TAG, "  -- CUR; not mAlways!");
18995                        } else {
18996                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18997                            Slog.i(TAG, "  -- CUR: mSet="
18998                                    + Arrays.toString(cur.mPref.mSetComponents));
18999                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19000                            Slog.i(TAG, "  -- NEW: mMatch="
19001                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19002                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19003                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19004                        }
19005                    }
19006                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19007                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19008                            && cur.mPref.sameSet(set)) {
19009                        // Setting the preferred activity to what it happens to be already
19010                        if (DEBUG_PREFERRED) {
19011                            Slog.i(TAG, "Replacing with same preferred activity "
19012                                    + cur.mPref.mShortComponent + " for user "
19013                                    + userId + ":");
19014                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19015                        }
19016                        return;
19017                    }
19018                }
19019
19020                if (existing != null) {
19021                    if (DEBUG_PREFERRED) {
19022                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19023                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19024                    }
19025                    for (int i = 0; i < existing.size(); i++) {
19026                        PreferredActivity pa = existing.get(i);
19027                        if (DEBUG_PREFERRED) {
19028                            Slog.i(TAG, "Removing existing preferred activity "
19029                                    + pa.mPref.mComponent + ":");
19030                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19031                        }
19032                        pir.removeFilter(pa);
19033                    }
19034                }
19035            }
19036            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19037                    "Replacing preferred");
19038        }
19039    }
19040
19041    @Override
19042    public void clearPackagePreferredActivities(String packageName) {
19043        final int uid = Binder.getCallingUid();
19044        // writer
19045        synchronized (mPackages) {
19046            PackageParser.Package pkg = mPackages.get(packageName);
19047            if (pkg == null || pkg.applicationInfo.uid != uid) {
19048                if (mContext.checkCallingOrSelfPermission(
19049                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19050                        != PackageManager.PERMISSION_GRANTED) {
19051                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19052                            < Build.VERSION_CODES.FROYO) {
19053                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19054                                + Binder.getCallingUid());
19055                        return;
19056                    }
19057                    mContext.enforceCallingOrSelfPermission(
19058                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19059                }
19060            }
19061
19062            int user = UserHandle.getCallingUserId();
19063            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19064                scheduleWritePackageRestrictionsLocked(user);
19065            }
19066        }
19067    }
19068
19069    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19070    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19071        ArrayList<PreferredActivity> removed = null;
19072        boolean changed = false;
19073        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19074            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19075            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19076            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19077                continue;
19078            }
19079            Iterator<PreferredActivity> it = pir.filterIterator();
19080            while (it.hasNext()) {
19081                PreferredActivity pa = it.next();
19082                // Mark entry for removal only if it matches the package name
19083                // and the entry is of type "always".
19084                if (packageName == null ||
19085                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19086                                && pa.mPref.mAlways)) {
19087                    if (removed == null) {
19088                        removed = new ArrayList<PreferredActivity>();
19089                    }
19090                    removed.add(pa);
19091                }
19092            }
19093            if (removed != null) {
19094                for (int j=0; j<removed.size(); j++) {
19095                    PreferredActivity pa = removed.get(j);
19096                    pir.removeFilter(pa);
19097                }
19098                changed = true;
19099            }
19100        }
19101        if (changed) {
19102            postPreferredActivityChangedBroadcast(userId);
19103        }
19104        return changed;
19105    }
19106
19107    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19108    private void clearIntentFilterVerificationsLPw(int userId) {
19109        final int packageCount = mPackages.size();
19110        for (int i = 0; i < packageCount; i++) {
19111            PackageParser.Package pkg = mPackages.valueAt(i);
19112            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19113        }
19114    }
19115
19116    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19117    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19118        if (userId == UserHandle.USER_ALL) {
19119            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19120                    sUserManager.getUserIds())) {
19121                for (int oneUserId : sUserManager.getUserIds()) {
19122                    scheduleWritePackageRestrictionsLocked(oneUserId);
19123                }
19124            }
19125        } else {
19126            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19127                scheduleWritePackageRestrictionsLocked(userId);
19128            }
19129        }
19130    }
19131
19132    void clearDefaultBrowserIfNeeded(String packageName) {
19133        for (int oneUserId : sUserManager.getUserIds()) {
19134            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19135            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19136            if (packageName.equals(defaultBrowserPackageName)) {
19137                setDefaultBrowserPackageName(null, oneUserId);
19138            }
19139        }
19140    }
19141
19142    @Override
19143    public void resetApplicationPreferences(int userId) {
19144        mContext.enforceCallingOrSelfPermission(
19145                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19146        final long identity = Binder.clearCallingIdentity();
19147        // writer
19148        try {
19149            synchronized (mPackages) {
19150                clearPackagePreferredActivitiesLPw(null, userId);
19151                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19152                // TODO: We have to reset the default SMS and Phone. This requires
19153                // significant refactoring to keep all default apps in the package
19154                // manager (cleaner but more work) or have the services provide
19155                // callbacks to the package manager to request a default app reset.
19156                applyFactoryDefaultBrowserLPw(userId);
19157                clearIntentFilterVerificationsLPw(userId);
19158                primeDomainVerificationsLPw(userId);
19159                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19160                scheduleWritePackageRestrictionsLocked(userId);
19161            }
19162            resetNetworkPolicies(userId);
19163        } finally {
19164            Binder.restoreCallingIdentity(identity);
19165        }
19166    }
19167
19168    @Override
19169    public int getPreferredActivities(List<IntentFilter> outFilters,
19170            List<ComponentName> outActivities, String packageName) {
19171
19172        int num = 0;
19173        final int userId = UserHandle.getCallingUserId();
19174        // reader
19175        synchronized (mPackages) {
19176            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19177            if (pir != null) {
19178                final Iterator<PreferredActivity> it = pir.filterIterator();
19179                while (it.hasNext()) {
19180                    final PreferredActivity pa = it.next();
19181                    if (packageName == null
19182                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19183                                    && pa.mPref.mAlways)) {
19184                        if (outFilters != null) {
19185                            outFilters.add(new IntentFilter(pa));
19186                        }
19187                        if (outActivities != null) {
19188                            outActivities.add(pa.mPref.mComponent);
19189                        }
19190                    }
19191                }
19192            }
19193        }
19194
19195        return num;
19196    }
19197
19198    @Override
19199    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19200            int userId) {
19201        int callingUid = Binder.getCallingUid();
19202        if (callingUid != Process.SYSTEM_UID) {
19203            throw new SecurityException(
19204                    "addPersistentPreferredActivity can only be run by the system");
19205        }
19206        if (filter.countActions() == 0) {
19207            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19208            return;
19209        }
19210        synchronized (mPackages) {
19211            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19212                    ":");
19213            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19214            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19215                    new PersistentPreferredActivity(filter, activity));
19216            scheduleWritePackageRestrictionsLocked(userId);
19217            postPreferredActivityChangedBroadcast(userId);
19218        }
19219    }
19220
19221    @Override
19222    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19223        int callingUid = Binder.getCallingUid();
19224        if (callingUid != Process.SYSTEM_UID) {
19225            throw new SecurityException(
19226                    "clearPackagePersistentPreferredActivities can only be run by the system");
19227        }
19228        ArrayList<PersistentPreferredActivity> removed = null;
19229        boolean changed = false;
19230        synchronized (mPackages) {
19231            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19232                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19233                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19234                        .valueAt(i);
19235                if (userId != thisUserId) {
19236                    continue;
19237                }
19238                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19239                while (it.hasNext()) {
19240                    PersistentPreferredActivity ppa = it.next();
19241                    // Mark entry for removal only if it matches the package name.
19242                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19243                        if (removed == null) {
19244                            removed = new ArrayList<PersistentPreferredActivity>();
19245                        }
19246                        removed.add(ppa);
19247                    }
19248                }
19249                if (removed != null) {
19250                    for (int j=0; j<removed.size(); j++) {
19251                        PersistentPreferredActivity ppa = removed.get(j);
19252                        ppir.removeFilter(ppa);
19253                    }
19254                    changed = true;
19255                }
19256            }
19257
19258            if (changed) {
19259                scheduleWritePackageRestrictionsLocked(userId);
19260                postPreferredActivityChangedBroadcast(userId);
19261            }
19262        }
19263    }
19264
19265    /**
19266     * Common machinery for picking apart a restored XML blob and passing
19267     * it to a caller-supplied functor to be applied to the running system.
19268     */
19269    private void restoreFromXml(XmlPullParser parser, int userId,
19270            String expectedStartTag, BlobXmlRestorer functor)
19271            throws IOException, XmlPullParserException {
19272        int type;
19273        while ((type = parser.next()) != XmlPullParser.START_TAG
19274                && type != XmlPullParser.END_DOCUMENT) {
19275        }
19276        if (type != XmlPullParser.START_TAG) {
19277            // oops didn't find a start tag?!
19278            if (DEBUG_BACKUP) {
19279                Slog.e(TAG, "Didn't find start tag during restore");
19280            }
19281            return;
19282        }
19283Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19284        // this is supposed to be TAG_PREFERRED_BACKUP
19285        if (!expectedStartTag.equals(parser.getName())) {
19286            if (DEBUG_BACKUP) {
19287                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19288            }
19289            return;
19290        }
19291
19292        // skip interfering stuff, then we're aligned with the backing implementation
19293        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19294Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19295        functor.apply(parser, userId);
19296    }
19297
19298    private interface BlobXmlRestorer {
19299        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19300    }
19301
19302    /**
19303     * Non-Binder method, support for the backup/restore mechanism: write the
19304     * full set of preferred activities in its canonical XML format.  Returns the
19305     * XML output as a byte array, or null if there is none.
19306     */
19307    @Override
19308    public byte[] getPreferredActivityBackup(int userId) {
19309        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19310            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19311        }
19312
19313        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19314        try {
19315            final XmlSerializer serializer = new FastXmlSerializer();
19316            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19317            serializer.startDocument(null, true);
19318            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19319
19320            synchronized (mPackages) {
19321                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19322            }
19323
19324            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19325            serializer.endDocument();
19326            serializer.flush();
19327        } catch (Exception e) {
19328            if (DEBUG_BACKUP) {
19329                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19330            }
19331            return null;
19332        }
19333
19334        return dataStream.toByteArray();
19335    }
19336
19337    @Override
19338    public void restorePreferredActivities(byte[] backup, int userId) {
19339        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19340            throw new SecurityException("Only the system may call restorePreferredActivities()");
19341        }
19342
19343        try {
19344            final XmlPullParser parser = Xml.newPullParser();
19345            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19346            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19347                    new BlobXmlRestorer() {
19348                        @Override
19349                        public void apply(XmlPullParser parser, int userId)
19350                                throws XmlPullParserException, IOException {
19351                            synchronized (mPackages) {
19352                                mSettings.readPreferredActivitiesLPw(parser, userId);
19353                            }
19354                        }
19355                    } );
19356        } catch (Exception e) {
19357            if (DEBUG_BACKUP) {
19358                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19359            }
19360        }
19361    }
19362
19363    /**
19364     * Non-Binder method, support for the backup/restore mechanism: write the
19365     * default browser (etc) settings in its canonical XML format.  Returns the default
19366     * browser XML representation as a byte array, or null if there is none.
19367     */
19368    @Override
19369    public byte[] getDefaultAppsBackup(int userId) {
19370        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19371            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19372        }
19373
19374        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19375        try {
19376            final XmlSerializer serializer = new FastXmlSerializer();
19377            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19378            serializer.startDocument(null, true);
19379            serializer.startTag(null, TAG_DEFAULT_APPS);
19380
19381            synchronized (mPackages) {
19382                mSettings.writeDefaultAppsLPr(serializer, userId);
19383            }
19384
19385            serializer.endTag(null, TAG_DEFAULT_APPS);
19386            serializer.endDocument();
19387            serializer.flush();
19388        } catch (Exception e) {
19389            if (DEBUG_BACKUP) {
19390                Slog.e(TAG, "Unable to write default apps for backup", e);
19391            }
19392            return null;
19393        }
19394
19395        return dataStream.toByteArray();
19396    }
19397
19398    @Override
19399    public void restoreDefaultApps(byte[] backup, int userId) {
19400        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19401            throw new SecurityException("Only the system may call restoreDefaultApps()");
19402        }
19403
19404        try {
19405            final XmlPullParser parser = Xml.newPullParser();
19406            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19407            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19408                    new BlobXmlRestorer() {
19409                        @Override
19410                        public void apply(XmlPullParser parser, int userId)
19411                                throws XmlPullParserException, IOException {
19412                            synchronized (mPackages) {
19413                                mSettings.readDefaultAppsLPw(parser, userId);
19414                            }
19415                        }
19416                    } );
19417        } catch (Exception e) {
19418            if (DEBUG_BACKUP) {
19419                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19420            }
19421        }
19422    }
19423
19424    @Override
19425    public byte[] getIntentFilterVerificationBackup(int userId) {
19426        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19427            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19428        }
19429
19430        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19431        try {
19432            final XmlSerializer serializer = new FastXmlSerializer();
19433            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19434            serializer.startDocument(null, true);
19435            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19436
19437            synchronized (mPackages) {
19438                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19439            }
19440
19441            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19442            serializer.endDocument();
19443            serializer.flush();
19444        } catch (Exception e) {
19445            if (DEBUG_BACKUP) {
19446                Slog.e(TAG, "Unable to write default apps for backup", e);
19447            }
19448            return null;
19449        }
19450
19451        return dataStream.toByteArray();
19452    }
19453
19454    @Override
19455    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19456        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19457            throw new SecurityException("Only the system may call restorePreferredActivities()");
19458        }
19459
19460        try {
19461            final XmlPullParser parser = Xml.newPullParser();
19462            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19463            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19464                    new BlobXmlRestorer() {
19465                        @Override
19466                        public void apply(XmlPullParser parser, int userId)
19467                                throws XmlPullParserException, IOException {
19468                            synchronized (mPackages) {
19469                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19470                                mSettings.writeLPr();
19471                            }
19472                        }
19473                    } );
19474        } catch (Exception e) {
19475            if (DEBUG_BACKUP) {
19476                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19477            }
19478        }
19479    }
19480
19481    @Override
19482    public byte[] getPermissionGrantBackup(int userId) {
19483        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19484            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19485        }
19486
19487        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19488        try {
19489            final XmlSerializer serializer = new FastXmlSerializer();
19490            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19491            serializer.startDocument(null, true);
19492            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19493
19494            synchronized (mPackages) {
19495                serializeRuntimePermissionGrantsLPr(serializer, userId);
19496            }
19497
19498            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19499            serializer.endDocument();
19500            serializer.flush();
19501        } catch (Exception e) {
19502            if (DEBUG_BACKUP) {
19503                Slog.e(TAG, "Unable to write default apps for backup", e);
19504            }
19505            return null;
19506        }
19507
19508        return dataStream.toByteArray();
19509    }
19510
19511    @Override
19512    public void restorePermissionGrants(byte[] backup, int userId) {
19513        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19514            throw new SecurityException("Only the system may call restorePermissionGrants()");
19515        }
19516
19517        try {
19518            final XmlPullParser parser = Xml.newPullParser();
19519            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19520            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19521                    new BlobXmlRestorer() {
19522                        @Override
19523                        public void apply(XmlPullParser parser, int userId)
19524                                throws XmlPullParserException, IOException {
19525                            synchronized (mPackages) {
19526                                processRestoredPermissionGrantsLPr(parser, userId);
19527                            }
19528                        }
19529                    } );
19530        } catch (Exception e) {
19531            if (DEBUG_BACKUP) {
19532                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19533            }
19534        }
19535    }
19536
19537    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19538            throws IOException {
19539        serializer.startTag(null, TAG_ALL_GRANTS);
19540
19541        final int N = mSettings.mPackages.size();
19542        for (int i = 0; i < N; i++) {
19543            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19544            boolean pkgGrantsKnown = false;
19545
19546            PermissionsState packagePerms = ps.getPermissionsState();
19547
19548            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19549                final int grantFlags = state.getFlags();
19550                // only look at grants that are not system/policy fixed
19551                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19552                    final boolean isGranted = state.isGranted();
19553                    // And only back up the user-twiddled state bits
19554                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19555                        final String packageName = mSettings.mPackages.keyAt(i);
19556                        if (!pkgGrantsKnown) {
19557                            serializer.startTag(null, TAG_GRANT);
19558                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19559                            pkgGrantsKnown = true;
19560                        }
19561
19562                        final boolean userSet =
19563                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19564                        final boolean userFixed =
19565                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19566                        final boolean revoke =
19567                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19568
19569                        serializer.startTag(null, TAG_PERMISSION);
19570                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19571                        if (isGranted) {
19572                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19573                        }
19574                        if (userSet) {
19575                            serializer.attribute(null, ATTR_USER_SET, "true");
19576                        }
19577                        if (userFixed) {
19578                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19579                        }
19580                        if (revoke) {
19581                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19582                        }
19583                        serializer.endTag(null, TAG_PERMISSION);
19584                    }
19585                }
19586            }
19587
19588            if (pkgGrantsKnown) {
19589                serializer.endTag(null, TAG_GRANT);
19590            }
19591        }
19592
19593        serializer.endTag(null, TAG_ALL_GRANTS);
19594    }
19595
19596    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19597            throws XmlPullParserException, IOException {
19598        String pkgName = null;
19599        int outerDepth = parser.getDepth();
19600        int type;
19601        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19602                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19603            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19604                continue;
19605            }
19606
19607            final String tagName = parser.getName();
19608            if (tagName.equals(TAG_GRANT)) {
19609                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19610                if (DEBUG_BACKUP) {
19611                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19612                }
19613            } else if (tagName.equals(TAG_PERMISSION)) {
19614
19615                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19616                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19617
19618                int newFlagSet = 0;
19619                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19620                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19621                }
19622                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19623                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19624                }
19625                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19626                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19627                }
19628                if (DEBUG_BACKUP) {
19629                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19630                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19631                }
19632                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19633                if (ps != null) {
19634                    // Already installed so we apply the grant immediately
19635                    if (DEBUG_BACKUP) {
19636                        Slog.v(TAG, "        + already installed; applying");
19637                    }
19638                    PermissionsState perms = ps.getPermissionsState();
19639                    BasePermission bp = mSettings.mPermissions.get(permName);
19640                    if (bp != null) {
19641                        if (isGranted) {
19642                            perms.grantRuntimePermission(bp, userId);
19643                        }
19644                        if (newFlagSet != 0) {
19645                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19646                        }
19647                    }
19648                } else {
19649                    // Need to wait for post-restore install to apply the grant
19650                    if (DEBUG_BACKUP) {
19651                        Slog.v(TAG, "        - not yet installed; saving for later");
19652                    }
19653                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19654                            isGranted, newFlagSet, userId);
19655                }
19656            } else {
19657                PackageManagerService.reportSettingsProblem(Log.WARN,
19658                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19659                XmlUtils.skipCurrentTag(parser);
19660            }
19661        }
19662
19663        scheduleWriteSettingsLocked();
19664        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19665    }
19666
19667    @Override
19668    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19669            int sourceUserId, int targetUserId, int flags) {
19670        mContext.enforceCallingOrSelfPermission(
19671                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19672        int callingUid = Binder.getCallingUid();
19673        enforceOwnerRights(ownerPackage, callingUid);
19674        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19675        if (intentFilter.countActions() == 0) {
19676            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19677            return;
19678        }
19679        synchronized (mPackages) {
19680            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19681                    ownerPackage, targetUserId, flags);
19682            CrossProfileIntentResolver resolver =
19683                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19684            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19685            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19686            if (existing != null) {
19687                int size = existing.size();
19688                for (int i = 0; i < size; i++) {
19689                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19690                        return;
19691                    }
19692                }
19693            }
19694            resolver.addFilter(newFilter);
19695            scheduleWritePackageRestrictionsLocked(sourceUserId);
19696        }
19697    }
19698
19699    @Override
19700    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19701        mContext.enforceCallingOrSelfPermission(
19702                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19703        int callingUid = Binder.getCallingUid();
19704        enforceOwnerRights(ownerPackage, callingUid);
19705        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19706        synchronized (mPackages) {
19707            CrossProfileIntentResolver resolver =
19708                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19709            ArraySet<CrossProfileIntentFilter> set =
19710                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19711            for (CrossProfileIntentFilter filter : set) {
19712                if (filter.getOwnerPackage().equals(ownerPackage)) {
19713                    resolver.removeFilter(filter);
19714                }
19715            }
19716            scheduleWritePackageRestrictionsLocked(sourceUserId);
19717        }
19718    }
19719
19720    // Enforcing that callingUid is owning pkg on userId
19721    private void enforceOwnerRights(String pkg, int callingUid) {
19722        // The system owns everything.
19723        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19724            return;
19725        }
19726        int callingUserId = UserHandle.getUserId(callingUid);
19727        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19728        if (pi == null) {
19729            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19730                    + callingUserId);
19731        }
19732        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19733            throw new SecurityException("Calling uid " + callingUid
19734                    + " does not own package " + pkg);
19735        }
19736    }
19737
19738    @Override
19739    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19740        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19741    }
19742
19743    /**
19744     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19745     * then reports the most likely home activity or null if there are more than one.
19746     */
19747    public ComponentName getDefaultHomeActivity(int userId) {
19748        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19749        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19750        if (cn != null) {
19751            return cn;
19752        }
19753
19754        // Find the launcher with the highest priority and return that component if there are no
19755        // other home activity with the same priority.
19756        int lastPriority = Integer.MIN_VALUE;
19757        ComponentName lastComponent = null;
19758        final int size = allHomeCandidates.size();
19759        for (int i = 0; i < size; i++) {
19760            final ResolveInfo ri = allHomeCandidates.get(i);
19761            if (ri.priority > lastPriority) {
19762                lastComponent = ri.activityInfo.getComponentName();
19763                lastPriority = ri.priority;
19764            } else if (ri.priority == lastPriority) {
19765                // Two components found with same priority.
19766                lastComponent = null;
19767            }
19768        }
19769        return lastComponent;
19770    }
19771
19772    private Intent getHomeIntent() {
19773        Intent intent = new Intent(Intent.ACTION_MAIN);
19774        intent.addCategory(Intent.CATEGORY_HOME);
19775        intent.addCategory(Intent.CATEGORY_DEFAULT);
19776        return intent;
19777    }
19778
19779    private IntentFilter getHomeFilter() {
19780        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19781        filter.addCategory(Intent.CATEGORY_HOME);
19782        filter.addCategory(Intent.CATEGORY_DEFAULT);
19783        return filter;
19784    }
19785
19786    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19787            int userId) {
19788        Intent intent  = getHomeIntent();
19789        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19790                PackageManager.GET_META_DATA, userId);
19791        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19792                true, false, false, userId);
19793
19794        allHomeCandidates.clear();
19795        if (list != null) {
19796            for (ResolveInfo ri : list) {
19797                allHomeCandidates.add(ri);
19798            }
19799        }
19800        return (preferred == null || preferred.activityInfo == null)
19801                ? null
19802                : new ComponentName(preferred.activityInfo.packageName,
19803                        preferred.activityInfo.name);
19804    }
19805
19806    @Override
19807    public void setHomeActivity(ComponentName comp, int userId) {
19808        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19809        getHomeActivitiesAsUser(homeActivities, userId);
19810
19811        boolean found = false;
19812
19813        final int size = homeActivities.size();
19814        final ComponentName[] set = new ComponentName[size];
19815        for (int i = 0; i < size; i++) {
19816            final ResolveInfo candidate = homeActivities.get(i);
19817            final ActivityInfo info = candidate.activityInfo;
19818            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19819            set[i] = activityName;
19820            if (!found && activityName.equals(comp)) {
19821                found = true;
19822            }
19823        }
19824        if (!found) {
19825            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19826                    + userId);
19827        }
19828        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19829                set, comp, userId);
19830    }
19831
19832    private @Nullable String getSetupWizardPackageName() {
19833        final Intent intent = new Intent(Intent.ACTION_MAIN);
19834        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19835
19836        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19837                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19838                        | MATCH_DISABLED_COMPONENTS,
19839                UserHandle.myUserId());
19840        if (matches.size() == 1) {
19841            return matches.get(0).getComponentInfo().packageName;
19842        } else {
19843            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19844                    + ": matches=" + matches);
19845            return null;
19846        }
19847    }
19848
19849    private @Nullable String getStorageManagerPackageName() {
19850        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19851
19852        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19853                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19854                        | MATCH_DISABLED_COMPONENTS,
19855                UserHandle.myUserId());
19856        if (matches.size() == 1) {
19857            return matches.get(0).getComponentInfo().packageName;
19858        } else {
19859            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19860                    + matches.size() + ": matches=" + matches);
19861            return null;
19862        }
19863    }
19864
19865    @Override
19866    public void setApplicationEnabledSetting(String appPackageName,
19867            int newState, int flags, int userId, String callingPackage) {
19868        if (!sUserManager.exists(userId)) return;
19869        if (callingPackage == null) {
19870            callingPackage = Integer.toString(Binder.getCallingUid());
19871        }
19872        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19873    }
19874
19875    @Override
19876    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19877        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19878        synchronized (mPackages) {
19879            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19880            if (pkgSetting != null) {
19881                pkgSetting.setUpdateAvailable(updateAvailable);
19882            }
19883        }
19884    }
19885
19886    @Override
19887    public void setComponentEnabledSetting(ComponentName componentName,
19888            int newState, int flags, int userId) {
19889        if (!sUserManager.exists(userId)) return;
19890        setEnabledSetting(componentName.getPackageName(),
19891                componentName.getClassName(), newState, flags, userId, null);
19892    }
19893
19894    private void setEnabledSetting(final String packageName, String className, int newState,
19895            final int flags, int userId, String callingPackage) {
19896        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19897              || newState == COMPONENT_ENABLED_STATE_ENABLED
19898              || newState == COMPONENT_ENABLED_STATE_DISABLED
19899              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19900              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19901            throw new IllegalArgumentException("Invalid new component state: "
19902                    + newState);
19903        }
19904        PackageSetting pkgSetting;
19905        final int uid = Binder.getCallingUid();
19906        final int permission;
19907        if (uid == Process.SYSTEM_UID) {
19908            permission = PackageManager.PERMISSION_GRANTED;
19909        } else {
19910            permission = mContext.checkCallingOrSelfPermission(
19911                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19912        }
19913        enforceCrossUserPermission(uid, userId,
19914                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19915        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19916        boolean sendNow = false;
19917        boolean isApp = (className == null);
19918        String componentName = isApp ? packageName : className;
19919        int packageUid = -1;
19920        ArrayList<String> components;
19921
19922        // writer
19923        synchronized (mPackages) {
19924            pkgSetting = mSettings.mPackages.get(packageName);
19925            if (pkgSetting == null) {
19926                if (className == null) {
19927                    throw new IllegalArgumentException("Unknown package: " + packageName);
19928                }
19929                throw new IllegalArgumentException(
19930                        "Unknown component: " + packageName + "/" + className);
19931            }
19932        }
19933
19934        // Limit who can change which apps
19935        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19936            // Don't allow apps that don't have permission to modify other apps
19937            if (!allowedByPermission) {
19938                throw new SecurityException(
19939                        "Permission Denial: attempt to change component state from pid="
19940                        + Binder.getCallingPid()
19941                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19942            }
19943            // Don't allow changing protected packages.
19944            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19945                throw new SecurityException("Cannot disable a protected package: " + packageName);
19946            }
19947        }
19948
19949        synchronized (mPackages) {
19950            if (uid == Process.SHELL_UID
19951                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19952                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19953                // unless it is a test package.
19954                int oldState = pkgSetting.getEnabled(userId);
19955                if (className == null
19956                    &&
19957                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19958                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19959                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19960                    &&
19961                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19962                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19963                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19964                    // ok
19965                } else {
19966                    throw new SecurityException(
19967                            "Shell cannot change component state for " + packageName + "/"
19968                            + className + " to " + newState);
19969                }
19970            }
19971            if (className == null) {
19972                // We're dealing with an application/package level state change
19973                if (pkgSetting.getEnabled(userId) == newState) {
19974                    // Nothing to do
19975                    return;
19976                }
19977                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19978                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19979                    // Don't care about who enables an app.
19980                    callingPackage = null;
19981                }
19982                pkgSetting.setEnabled(newState, userId, callingPackage);
19983                // pkgSetting.pkg.mSetEnabled = newState;
19984            } else {
19985                // We're dealing with a component level state change
19986                // First, verify that this is a valid class name.
19987                PackageParser.Package pkg = pkgSetting.pkg;
19988                if (pkg == null || !pkg.hasComponentClassName(className)) {
19989                    if (pkg != null &&
19990                            pkg.applicationInfo.targetSdkVersion >=
19991                                    Build.VERSION_CODES.JELLY_BEAN) {
19992                        throw new IllegalArgumentException("Component class " + className
19993                                + " does not exist in " + packageName);
19994                    } else {
19995                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19996                                + className + " does not exist in " + packageName);
19997                    }
19998                }
19999                switch (newState) {
20000                case COMPONENT_ENABLED_STATE_ENABLED:
20001                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20002                        return;
20003                    }
20004                    break;
20005                case COMPONENT_ENABLED_STATE_DISABLED:
20006                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20007                        return;
20008                    }
20009                    break;
20010                case COMPONENT_ENABLED_STATE_DEFAULT:
20011                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20012                        return;
20013                    }
20014                    break;
20015                default:
20016                    Slog.e(TAG, "Invalid new component state: " + newState);
20017                    return;
20018                }
20019            }
20020            scheduleWritePackageRestrictionsLocked(userId);
20021            updateSequenceNumberLP(packageName, new int[] { userId });
20022            final long callingId = Binder.clearCallingIdentity();
20023            try {
20024                updateInstantAppInstallerLocked();
20025            } finally {
20026                Binder.restoreCallingIdentity(callingId);
20027            }
20028            components = mPendingBroadcasts.get(userId, packageName);
20029            final boolean newPackage = components == null;
20030            if (newPackage) {
20031                components = new ArrayList<String>();
20032            }
20033            if (!components.contains(componentName)) {
20034                components.add(componentName);
20035            }
20036            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20037                sendNow = true;
20038                // Purge entry from pending broadcast list if another one exists already
20039                // since we are sending one right away.
20040                mPendingBroadcasts.remove(userId, packageName);
20041            } else {
20042                if (newPackage) {
20043                    mPendingBroadcasts.put(userId, packageName, components);
20044                }
20045                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20046                    // Schedule a message
20047                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20048                }
20049            }
20050        }
20051
20052        long callingId = Binder.clearCallingIdentity();
20053        try {
20054            if (sendNow) {
20055                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20056                sendPackageChangedBroadcast(packageName,
20057                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20058            }
20059        } finally {
20060            Binder.restoreCallingIdentity(callingId);
20061        }
20062    }
20063
20064    @Override
20065    public void flushPackageRestrictionsAsUser(int userId) {
20066        if (!sUserManager.exists(userId)) {
20067            return;
20068        }
20069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20070                false /* checkShell */, "flushPackageRestrictions");
20071        synchronized (mPackages) {
20072            mSettings.writePackageRestrictionsLPr(userId);
20073            mDirtyUsers.remove(userId);
20074            if (mDirtyUsers.isEmpty()) {
20075                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20076            }
20077        }
20078    }
20079
20080    private void sendPackageChangedBroadcast(String packageName,
20081            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20082        if (DEBUG_INSTALL)
20083            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20084                    + componentNames);
20085        Bundle extras = new Bundle(4);
20086        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20087        String nameList[] = new String[componentNames.size()];
20088        componentNames.toArray(nameList);
20089        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20090        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20091        extras.putInt(Intent.EXTRA_UID, packageUid);
20092        // If this is not reporting a change of the overall package, then only send it
20093        // to registered receivers.  We don't want to launch a swath of apps for every
20094        // little component state change.
20095        final int flags = !componentNames.contains(packageName)
20096                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20097        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20098                new int[] {UserHandle.getUserId(packageUid)});
20099    }
20100
20101    @Override
20102    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20103        if (!sUserManager.exists(userId)) return;
20104        final int uid = Binder.getCallingUid();
20105        final int permission = mContext.checkCallingOrSelfPermission(
20106                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20107        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20108        enforceCrossUserPermission(uid, userId,
20109                true /* requireFullPermission */, true /* checkShell */, "stop package");
20110        // writer
20111        synchronized (mPackages) {
20112            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20113                    allowedByPermission, uid, userId)) {
20114                scheduleWritePackageRestrictionsLocked(userId);
20115            }
20116        }
20117    }
20118
20119    @Override
20120    public String getInstallerPackageName(String packageName) {
20121        // reader
20122        synchronized (mPackages) {
20123            return mSettings.getInstallerPackageNameLPr(packageName);
20124        }
20125    }
20126
20127    public boolean isOrphaned(String packageName) {
20128        // reader
20129        synchronized (mPackages) {
20130            return mSettings.isOrphaned(packageName);
20131        }
20132    }
20133
20134    @Override
20135    public int getApplicationEnabledSetting(String packageName, int userId) {
20136        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20137        int uid = Binder.getCallingUid();
20138        enforceCrossUserPermission(uid, userId,
20139                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20140        // reader
20141        synchronized (mPackages) {
20142            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20143        }
20144    }
20145
20146    @Override
20147    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20148        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20149        int uid = Binder.getCallingUid();
20150        enforceCrossUserPermission(uid, userId,
20151                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20152        // reader
20153        synchronized (mPackages) {
20154            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20155        }
20156    }
20157
20158    @Override
20159    public void enterSafeMode() {
20160        enforceSystemOrRoot("Only the system can request entering safe mode");
20161
20162        if (!mSystemReady) {
20163            mSafeMode = true;
20164        }
20165    }
20166
20167    @Override
20168    public void systemReady() {
20169        mSystemReady = true;
20170
20171        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20172        // disabled after already being started.
20173        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20174                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20175
20176        // Read the compatibilty setting when the system is ready.
20177        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20178                mContext.getContentResolver(),
20179                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20180        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20181        if (DEBUG_SETTINGS) {
20182            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20183        }
20184
20185        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20186
20187        synchronized (mPackages) {
20188            // Verify that all of the preferred activity components actually
20189            // exist.  It is possible for applications to be updated and at
20190            // that point remove a previously declared activity component that
20191            // had been set as a preferred activity.  We try to clean this up
20192            // the next time we encounter that preferred activity, but it is
20193            // possible for the user flow to never be able to return to that
20194            // situation so here we do a sanity check to make sure we haven't
20195            // left any junk around.
20196            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20197            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20198                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20199                removed.clear();
20200                for (PreferredActivity pa : pir.filterSet()) {
20201                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20202                        removed.add(pa);
20203                    }
20204                }
20205                if (removed.size() > 0) {
20206                    for (int r=0; r<removed.size(); r++) {
20207                        PreferredActivity pa = removed.get(r);
20208                        Slog.w(TAG, "Removing dangling preferred activity: "
20209                                + pa.mPref.mComponent);
20210                        pir.removeFilter(pa);
20211                    }
20212                    mSettings.writePackageRestrictionsLPr(
20213                            mSettings.mPreferredActivities.keyAt(i));
20214                }
20215            }
20216
20217            for (int userId : UserManagerService.getInstance().getUserIds()) {
20218                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20219                    grantPermissionsUserIds = ArrayUtils.appendInt(
20220                            grantPermissionsUserIds, userId);
20221                }
20222            }
20223        }
20224        sUserManager.systemReady();
20225
20226        // If we upgraded grant all default permissions before kicking off.
20227        for (int userId : grantPermissionsUserIds) {
20228            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20229        }
20230
20231        // If we did not grant default permissions, we preload from this the
20232        // default permission exceptions lazily to ensure we don't hit the
20233        // disk on a new user creation.
20234        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20235            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20236        }
20237
20238        // Kick off any messages waiting for system ready
20239        if (mPostSystemReadyMessages != null) {
20240            for (Message msg : mPostSystemReadyMessages) {
20241                msg.sendToTarget();
20242            }
20243            mPostSystemReadyMessages = null;
20244        }
20245
20246        // Watch for external volumes that come and go over time
20247        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20248        storage.registerListener(mStorageListener);
20249
20250        mInstallerService.systemReady();
20251        mPackageDexOptimizer.systemReady();
20252
20253        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20254                StorageManagerInternal.class);
20255        StorageManagerInternal.addExternalStoragePolicy(
20256                new StorageManagerInternal.ExternalStorageMountPolicy() {
20257            @Override
20258            public int getMountMode(int uid, String packageName) {
20259                if (Process.isIsolated(uid)) {
20260                    return Zygote.MOUNT_EXTERNAL_NONE;
20261                }
20262                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20263                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20264                }
20265                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20266                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20267                }
20268                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20269                    return Zygote.MOUNT_EXTERNAL_READ;
20270                }
20271                return Zygote.MOUNT_EXTERNAL_WRITE;
20272            }
20273
20274            @Override
20275            public boolean hasExternalStorage(int uid, String packageName) {
20276                return true;
20277            }
20278        });
20279
20280        // Now that we're mostly running, clean up stale users and apps
20281        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20282        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20283
20284        if (mPrivappPermissionsViolations != null) {
20285            Slog.wtf(TAG,"Signature|privileged permissions not in "
20286                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20287            mPrivappPermissionsViolations = null;
20288        }
20289    }
20290
20291    public void waitForAppDataPrepared() {
20292        if (mPrepareAppDataFuture == null) {
20293            return;
20294        }
20295        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20296        mPrepareAppDataFuture = null;
20297    }
20298
20299    @Override
20300    public boolean isSafeMode() {
20301        return mSafeMode;
20302    }
20303
20304    @Override
20305    public boolean hasSystemUidErrors() {
20306        return mHasSystemUidErrors;
20307    }
20308
20309    static String arrayToString(int[] array) {
20310        StringBuffer buf = new StringBuffer(128);
20311        buf.append('[');
20312        if (array != null) {
20313            for (int i=0; i<array.length; i++) {
20314                if (i > 0) buf.append(", ");
20315                buf.append(array[i]);
20316            }
20317        }
20318        buf.append(']');
20319        return buf.toString();
20320    }
20321
20322    static class DumpState {
20323        public static final int DUMP_LIBS = 1 << 0;
20324        public static final int DUMP_FEATURES = 1 << 1;
20325        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20326        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20327        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20328        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20329        public static final int DUMP_PERMISSIONS = 1 << 6;
20330        public static final int DUMP_PACKAGES = 1 << 7;
20331        public static final int DUMP_SHARED_USERS = 1 << 8;
20332        public static final int DUMP_MESSAGES = 1 << 9;
20333        public static final int DUMP_PROVIDERS = 1 << 10;
20334        public static final int DUMP_VERIFIERS = 1 << 11;
20335        public static final int DUMP_PREFERRED = 1 << 12;
20336        public static final int DUMP_PREFERRED_XML = 1 << 13;
20337        public static final int DUMP_KEYSETS = 1 << 14;
20338        public static final int DUMP_VERSION = 1 << 15;
20339        public static final int DUMP_INSTALLS = 1 << 16;
20340        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20341        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20342        public static final int DUMP_FROZEN = 1 << 19;
20343        public static final int DUMP_DEXOPT = 1 << 20;
20344        public static final int DUMP_COMPILER_STATS = 1 << 21;
20345        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20346
20347        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20348
20349        private int mTypes;
20350
20351        private int mOptions;
20352
20353        private boolean mTitlePrinted;
20354
20355        private SharedUserSetting mSharedUser;
20356
20357        public boolean isDumping(int type) {
20358            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20359                return true;
20360            }
20361
20362            return (mTypes & type) != 0;
20363        }
20364
20365        public void setDump(int type) {
20366            mTypes |= type;
20367        }
20368
20369        public boolean isOptionEnabled(int option) {
20370            return (mOptions & option) != 0;
20371        }
20372
20373        public void setOptionEnabled(int option) {
20374            mOptions |= option;
20375        }
20376
20377        public boolean onTitlePrinted() {
20378            final boolean printed = mTitlePrinted;
20379            mTitlePrinted = true;
20380            return printed;
20381        }
20382
20383        public boolean getTitlePrinted() {
20384            return mTitlePrinted;
20385        }
20386
20387        public void setTitlePrinted(boolean enabled) {
20388            mTitlePrinted = enabled;
20389        }
20390
20391        public SharedUserSetting getSharedUser() {
20392            return mSharedUser;
20393        }
20394
20395        public void setSharedUser(SharedUserSetting user) {
20396            mSharedUser = user;
20397        }
20398    }
20399
20400    @Override
20401    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20402            FileDescriptor err, String[] args, ShellCallback callback,
20403            ResultReceiver resultReceiver) {
20404        (new PackageManagerShellCommand(this)).exec(
20405                this, in, out, err, args, callback, resultReceiver);
20406    }
20407
20408    @Override
20409    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20410        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20411
20412        DumpState dumpState = new DumpState();
20413        boolean fullPreferred = false;
20414        boolean checkin = false;
20415
20416        String packageName = null;
20417        ArraySet<String> permissionNames = null;
20418
20419        int opti = 0;
20420        while (opti < args.length) {
20421            String opt = args[opti];
20422            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20423                break;
20424            }
20425            opti++;
20426
20427            if ("-a".equals(opt)) {
20428                // Right now we only know how to print all.
20429            } else if ("-h".equals(opt)) {
20430                pw.println("Package manager dump options:");
20431                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20432                pw.println("    --checkin: dump for a checkin");
20433                pw.println("    -f: print details of intent filters");
20434                pw.println("    -h: print this help");
20435                pw.println("  cmd may be one of:");
20436                pw.println("    l[ibraries]: list known shared libraries");
20437                pw.println("    f[eatures]: list device features");
20438                pw.println("    k[eysets]: print known keysets");
20439                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20440                pw.println("    perm[issions]: dump permissions");
20441                pw.println("    permission [name ...]: dump declaration and use of given permission");
20442                pw.println("    pref[erred]: print preferred package settings");
20443                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20444                pw.println("    prov[iders]: dump content providers");
20445                pw.println("    p[ackages]: dump installed packages");
20446                pw.println("    s[hared-users]: dump shared user IDs");
20447                pw.println("    m[essages]: print collected runtime messages");
20448                pw.println("    v[erifiers]: print package verifier info");
20449                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20450                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20451                pw.println("    version: print database version info");
20452                pw.println("    write: write current settings now");
20453                pw.println("    installs: details about install sessions");
20454                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20455                pw.println("    dexopt: dump dexopt state");
20456                pw.println("    compiler-stats: dump compiler statistics");
20457                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20458                pw.println("    <package.name>: info about given package");
20459                return;
20460            } else if ("--checkin".equals(opt)) {
20461                checkin = true;
20462            } else if ("-f".equals(opt)) {
20463                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20464            } else if ("--proto".equals(opt)) {
20465                dumpProto(fd);
20466                return;
20467            } else {
20468                pw.println("Unknown argument: " + opt + "; use -h for help");
20469            }
20470        }
20471
20472        // Is the caller requesting to dump a particular piece of data?
20473        if (opti < args.length) {
20474            String cmd = args[opti];
20475            opti++;
20476            // Is this a package name?
20477            if ("android".equals(cmd) || cmd.contains(".")) {
20478                packageName = cmd;
20479                // When dumping a single package, we always dump all of its
20480                // filter information since the amount of data will be reasonable.
20481                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20482            } else if ("check-permission".equals(cmd)) {
20483                if (opti >= args.length) {
20484                    pw.println("Error: check-permission missing permission argument");
20485                    return;
20486                }
20487                String perm = args[opti];
20488                opti++;
20489                if (opti >= args.length) {
20490                    pw.println("Error: check-permission missing package argument");
20491                    return;
20492                }
20493
20494                String pkg = args[opti];
20495                opti++;
20496                int user = UserHandle.getUserId(Binder.getCallingUid());
20497                if (opti < args.length) {
20498                    try {
20499                        user = Integer.parseInt(args[opti]);
20500                    } catch (NumberFormatException e) {
20501                        pw.println("Error: check-permission user argument is not a number: "
20502                                + args[opti]);
20503                        return;
20504                    }
20505                }
20506
20507                // Normalize package name to handle renamed packages and static libs
20508                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20509
20510                pw.println(checkPermission(perm, pkg, user));
20511                return;
20512            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20513                dumpState.setDump(DumpState.DUMP_LIBS);
20514            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20515                dumpState.setDump(DumpState.DUMP_FEATURES);
20516            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20517                if (opti >= args.length) {
20518                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20519                            | DumpState.DUMP_SERVICE_RESOLVERS
20520                            | DumpState.DUMP_RECEIVER_RESOLVERS
20521                            | DumpState.DUMP_CONTENT_RESOLVERS);
20522                } else {
20523                    while (opti < args.length) {
20524                        String name = args[opti];
20525                        if ("a".equals(name) || "activity".equals(name)) {
20526                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20527                        } else if ("s".equals(name) || "service".equals(name)) {
20528                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20529                        } else if ("r".equals(name) || "receiver".equals(name)) {
20530                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20531                        } else if ("c".equals(name) || "content".equals(name)) {
20532                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20533                        } else {
20534                            pw.println("Error: unknown resolver table type: " + name);
20535                            return;
20536                        }
20537                        opti++;
20538                    }
20539                }
20540            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20541                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20542            } else if ("permission".equals(cmd)) {
20543                if (opti >= args.length) {
20544                    pw.println("Error: permission requires permission name");
20545                    return;
20546                }
20547                permissionNames = new ArraySet<>();
20548                while (opti < args.length) {
20549                    permissionNames.add(args[opti]);
20550                    opti++;
20551                }
20552                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20553                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20554            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20555                dumpState.setDump(DumpState.DUMP_PREFERRED);
20556            } else if ("preferred-xml".equals(cmd)) {
20557                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20558                if (opti < args.length && "--full".equals(args[opti])) {
20559                    fullPreferred = true;
20560                    opti++;
20561                }
20562            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20563                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20564            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20565                dumpState.setDump(DumpState.DUMP_PACKAGES);
20566            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20567                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20568            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20569                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20570            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20571                dumpState.setDump(DumpState.DUMP_MESSAGES);
20572            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20573                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20574            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20575                    || "intent-filter-verifiers".equals(cmd)) {
20576                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20577            } else if ("version".equals(cmd)) {
20578                dumpState.setDump(DumpState.DUMP_VERSION);
20579            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20580                dumpState.setDump(DumpState.DUMP_KEYSETS);
20581            } else if ("installs".equals(cmd)) {
20582                dumpState.setDump(DumpState.DUMP_INSTALLS);
20583            } else if ("frozen".equals(cmd)) {
20584                dumpState.setDump(DumpState.DUMP_FROZEN);
20585            } else if ("dexopt".equals(cmd)) {
20586                dumpState.setDump(DumpState.DUMP_DEXOPT);
20587            } else if ("compiler-stats".equals(cmd)) {
20588                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20589            } else if ("enabled-overlays".equals(cmd)) {
20590                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20591            } else if ("write".equals(cmd)) {
20592                synchronized (mPackages) {
20593                    mSettings.writeLPr();
20594                    pw.println("Settings written.");
20595                    return;
20596                }
20597            }
20598        }
20599
20600        if (checkin) {
20601            pw.println("vers,1");
20602        }
20603
20604        // reader
20605        synchronized (mPackages) {
20606            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20607                if (!checkin) {
20608                    if (dumpState.onTitlePrinted())
20609                        pw.println();
20610                    pw.println("Database versions:");
20611                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20612                }
20613            }
20614
20615            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20616                if (!checkin) {
20617                    if (dumpState.onTitlePrinted())
20618                        pw.println();
20619                    pw.println("Verifiers:");
20620                    pw.print("  Required: ");
20621                    pw.print(mRequiredVerifierPackage);
20622                    pw.print(" (uid=");
20623                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20624                            UserHandle.USER_SYSTEM));
20625                    pw.println(")");
20626                } else if (mRequiredVerifierPackage != null) {
20627                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20628                    pw.print(",");
20629                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20630                            UserHandle.USER_SYSTEM));
20631                }
20632            }
20633
20634            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20635                    packageName == null) {
20636                if (mIntentFilterVerifierComponent != null) {
20637                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20638                    if (!checkin) {
20639                        if (dumpState.onTitlePrinted())
20640                            pw.println();
20641                        pw.println("Intent Filter Verifier:");
20642                        pw.print("  Using: ");
20643                        pw.print(verifierPackageName);
20644                        pw.print(" (uid=");
20645                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20646                                UserHandle.USER_SYSTEM));
20647                        pw.println(")");
20648                    } else if (verifierPackageName != null) {
20649                        pw.print("ifv,"); pw.print(verifierPackageName);
20650                        pw.print(",");
20651                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20652                                UserHandle.USER_SYSTEM));
20653                    }
20654                } else {
20655                    pw.println();
20656                    pw.println("No Intent Filter Verifier available!");
20657                }
20658            }
20659
20660            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20661                boolean printedHeader = false;
20662                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20663                while (it.hasNext()) {
20664                    String libName = it.next();
20665                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20666                    if (versionedLib == null) {
20667                        continue;
20668                    }
20669                    final int versionCount = versionedLib.size();
20670                    for (int i = 0; i < versionCount; i++) {
20671                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20672                        if (!checkin) {
20673                            if (!printedHeader) {
20674                                if (dumpState.onTitlePrinted())
20675                                    pw.println();
20676                                pw.println("Libraries:");
20677                                printedHeader = true;
20678                            }
20679                            pw.print("  ");
20680                        } else {
20681                            pw.print("lib,");
20682                        }
20683                        pw.print(libEntry.info.getName());
20684                        if (libEntry.info.isStatic()) {
20685                            pw.print(" version=" + libEntry.info.getVersion());
20686                        }
20687                        if (!checkin) {
20688                            pw.print(" -> ");
20689                        }
20690                        if (libEntry.path != null) {
20691                            pw.print(" (jar) ");
20692                            pw.print(libEntry.path);
20693                        } else {
20694                            pw.print(" (apk) ");
20695                            pw.print(libEntry.apk);
20696                        }
20697                        pw.println();
20698                    }
20699                }
20700            }
20701
20702            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20703                if (dumpState.onTitlePrinted())
20704                    pw.println();
20705                if (!checkin) {
20706                    pw.println("Features:");
20707                }
20708
20709                synchronized (mAvailableFeatures) {
20710                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20711                        if (checkin) {
20712                            pw.print("feat,");
20713                            pw.print(feat.name);
20714                            pw.print(",");
20715                            pw.println(feat.version);
20716                        } else {
20717                            pw.print("  ");
20718                            pw.print(feat.name);
20719                            if (feat.version > 0) {
20720                                pw.print(" version=");
20721                                pw.print(feat.version);
20722                            }
20723                            pw.println();
20724                        }
20725                    }
20726                }
20727            }
20728
20729            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20730                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20731                        : "Activity Resolver Table:", "  ", packageName,
20732                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20733                    dumpState.setTitlePrinted(true);
20734                }
20735            }
20736            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20737                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20738                        : "Receiver Resolver Table:", "  ", packageName,
20739                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20740                    dumpState.setTitlePrinted(true);
20741                }
20742            }
20743            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20744                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20745                        : "Service Resolver Table:", "  ", packageName,
20746                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20747                    dumpState.setTitlePrinted(true);
20748                }
20749            }
20750            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20751                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20752                        : "Provider Resolver Table:", "  ", packageName,
20753                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20754                    dumpState.setTitlePrinted(true);
20755                }
20756            }
20757
20758            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20759                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20760                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20761                    int user = mSettings.mPreferredActivities.keyAt(i);
20762                    if (pir.dump(pw,
20763                            dumpState.getTitlePrinted()
20764                                ? "\nPreferred Activities User " + user + ":"
20765                                : "Preferred Activities User " + user + ":", "  ",
20766                            packageName, true, false)) {
20767                        dumpState.setTitlePrinted(true);
20768                    }
20769                }
20770            }
20771
20772            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20773                pw.flush();
20774                FileOutputStream fout = new FileOutputStream(fd);
20775                BufferedOutputStream str = new BufferedOutputStream(fout);
20776                XmlSerializer serializer = new FastXmlSerializer();
20777                try {
20778                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20779                    serializer.startDocument(null, true);
20780                    serializer.setFeature(
20781                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20782                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20783                    serializer.endDocument();
20784                    serializer.flush();
20785                } catch (IllegalArgumentException e) {
20786                    pw.println("Failed writing: " + e);
20787                } catch (IllegalStateException e) {
20788                    pw.println("Failed writing: " + e);
20789                } catch (IOException e) {
20790                    pw.println("Failed writing: " + e);
20791                }
20792            }
20793
20794            if (!checkin
20795                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20796                    && packageName == null) {
20797                pw.println();
20798                int count = mSettings.mPackages.size();
20799                if (count == 0) {
20800                    pw.println("No applications!");
20801                    pw.println();
20802                } else {
20803                    final String prefix = "  ";
20804                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20805                    if (allPackageSettings.size() == 0) {
20806                        pw.println("No domain preferred apps!");
20807                        pw.println();
20808                    } else {
20809                        pw.println("App verification status:");
20810                        pw.println();
20811                        count = 0;
20812                        for (PackageSetting ps : allPackageSettings) {
20813                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20814                            if (ivi == null || ivi.getPackageName() == null) continue;
20815                            pw.println(prefix + "Package: " + ivi.getPackageName());
20816                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20817                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20818                            pw.println();
20819                            count++;
20820                        }
20821                        if (count == 0) {
20822                            pw.println(prefix + "No app verification established.");
20823                            pw.println();
20824                        }
20825                        for (int userId : sUserManager.getUserIds()) {
20826                            pw.println("App linkages for user " + userId + ":");
20827                            pw.println();
20828                            count = 0;
20829                            for (PackageSetting ps : allPackageSettings) {
20830                                final long status = ps.getDomainVerificationStatusForUser(userId);
20831                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20832                                        && !DEBUG_DOMAIN_VERIFICATION) {
20833                                    continue;
20834                                }
20835                                pw.println(prefix + "Package: " + ps.name);
20836                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20837                                String statusStr = IntentFilterVerificationInfo.
20838                                        getStatusStringFromValue(status);
20839                                pw.println(prefix + "Status:  " + statusStr);
20840                                pw.println();
20841                                count++;
20842                            }
20843                            if (count == 0) {
20844                                pw.println(prefix + "No configured app linkages.");
20845                                pw.println();
20846                            }
20847                        }
20848                    }
20849                }
20850            }
20851
20852            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20853                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20854                if (packageName == null && permissionNames == null) {
20855                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20856                        if (iperm == 0) {
20857                            if (dumpState.onTitlePrinted())
20858                                pw.println();
20859                            pw.println("AppOp Permissions:");
20860                        }
20861                        pw.print("  AppOp Permission ");
20862                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20863                        pw.println(":");
20864                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20865                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20866                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20867                        }
20868                    }
20869                }
20870            }
20871
20872            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20873                boolean printedSomething = false;
20874                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20875                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20876                        continue;
20877                    }
20878                    if (!printedSomething) {
20879                        if (dumpState.onTitlePrinted())
20880                            pw.println();
20881                        pw.println("Registered ContentProviders:");
20882                        printedSomething = true;
20883                    }
20884                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20885                    pw.print("    "); pw.println(p.toString());
20886                }
20887                printedSomething = false;
20888                for (Map.Entry<String, PackageParser.Provider> entry :
20889                        mProvidersByAuthority.entrySet()) {
20890                    PackageParser.Provider p = entry.getValue();
20891                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20892                        continue;
20893                    }
20894                    if (!printedSomething) {
20895                        if (dumpState.onTitlePrinted())
20896                            pw.println();
20897                        pw.println("ContentProvider Authorities:");
20898                        printedSomething = true;
20899                    }
20900                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20901                    pw.print("    "); pw.println(p.toString());
20902                    if (p.info != null && p.info.applicationInfo != null) {
20903                        final String appInfo = p.info.applicationInfo.toString();
20904                        pw.print("      applicationInfo="); pw.println(appInfo);
20905                    }
20906                }
20907            }
20908
20909            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20910                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20911            }
20912
20913            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20914                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20915            }
20916
20917            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20918                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20919            }
20920
20921            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20922                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20923            }
20924
20925            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20926                // XXX should handle packageName != null by dumping only install data that
20927                // the given package is involved with.
20928                if (dumpState.onTitlePrinted()) pw.println();
20929
20930                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20931                ipw.println();
20932                ipw.println("Frozen packages:");
20933                ipw.increaseIndent();
20934                if (mFrozenPackages.size() == 0) {
20935                    ipw.println("(none)");
20936                } else {
20937                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20938                        ipw.println(mFrozenPackages.valueAt(i));
20939                    }
20940                }
20941                ipw.decreaseIndent();
20942            }
20943
20944            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20945                if (dumpState.onTitlePrinted()) pw.println();
20946                dumpDexoptStateLPr(pw, packageName);
20947            }
20948
20949            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20950                if (dumpState.onTitlePrinted()) pw.println();
20951                dumpCompilerStatsLPr(pw, packageName);
20952            }
20953
20954            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20955                if (dumpState.onTitlePrinted()) pw.println();
20956                dumpEnabledOverlaysLPr(pw);
20957            }
20958
20959            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20960                if (dumpState.onTitlePrinted()) pw.println();
20961                mSettings.dumpReadMessagesLPr(pw, dumpState);
20962
20963                pw.println();
20964                pw.println("Package warning messages:");
20965                BufferedReader in = null;
20966                String line = null;
20967                try {
20968                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20969                    while ((line = in.readLine()) != null) {
20970                        if (line.contains("ignored: updated version")) continue;
20971                        pw.println(line);
20972                    }
20973                } catch (IOException ignored) {
20974                } finally {
20975                    IoUtils.closeQuietly(in);
20976                }
20977            }
20978
20979            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20980                BufferedReader in = null;
20981                String line = null;
20982                try {
20983                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20984                    while ((line = in.readLine()) != null) {
20985                        if (line.contains("ignored: updated version")) continue;
20986                        pw.print("msg,");
20987                        pw.println(line);
20988                    }
20989                } catch (IOException ignored) {
20990                } finally {
20991                    IoUtils.closeQuietly(in);
20992                }
20993            }
20994        }
20995
20996        // PackageInstaller should be called outside of mPackages lock
20997        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20998            // XXX should handle packageName != null by dumping only install data that
20999            // the given package is involved with.
21000            if (dumpState.onTitlePrinted()) pw.println();
21001            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21002        }
21003    }
21004
21005    private void dumpProto(FileDescriptor fd) {
21006        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21007
21008        synchronized (mPackages) {
21009            final long requiredVerifierPackageToken =
21010                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21011            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21012            proto.write(
21013                    PackageServiceDumpProto.PackageShortProto.UID,
21014                    getPackageUid(
21015                            mRequiredVerifierPackage,
21016                            MATCH_DEBUG_TRIAGED_MISSING,
21017                            UserHandle.USER_SYSTEM));
21018            proto.end(requiredVerifierPackageToken);
21019
21020            if (mIntentFilterVerifierComponent != null) {
21021                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21022                final long verifierPackageToken =
21023                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21024                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21025                proto.write(
21026                        PackageServiceDumpProto.PackageShortProto.UID,
21027                        getPackageUid(
21028                                verifierPackageName,
21029                                MATCH_DEBUG_TRIAGED_MISSING,
21030                                UserHandle.USER_SYSTEM));
21031                proto.end(verifierPackageToken);
21032            }
21033
21034            dumpSharedLibrariesProto(proto);
21035            dumpFeaturesProto(proto);
21036            mSettings.dumpPackagesProto(proto);
21037            mSettings.dumpSharedUsersProto(proto);
21038            dumpMessagesProto(proto);
21039        }
21040        proto.flush();
21041    }
21042
21043    private void dumpMessagesProto(ProtoOutputStream proto) {
21044        BufferedReader in = null;
21045        String line = null;
21046        try {
21047            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21048            while ((line = in.readLine()) != null) {
21049                if (line.contains("ignored: updated version")) continue;
21050                proto.write(PackageServiceDumpProto.MESSAGES, line);
21051            }
21052        } catch (IOException ignored) {
21053        } finally {
21054            IoUtils.closeQuietly(in);
21055        }
21056    }
21057
21058    private void dumpFeaturesProto(ProtoOutputStream proto) {
21059        synchronized (mAvailableFeatures) {
21060            final int count = mAvailableFeatures.size();
21061            for (int i = 0; i < count; i++) {
21062                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21063                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21064                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21065                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21066                proto.end(featureToken);
21067            }
21068        }
21069    }
21070
21071    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21072        final int count = mSharedLibraries.size();
21073        for (int i = 0; i < count; i++) {
21074            final String libName = mSharedLibraries.keyAt(i);
21075            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21076            if (versionedLib == null) {
21077                continue;
21078            }
21079            final int versionCount = versionedLib.size();
21080            for (int j = 0; j < versionCount; j++) {
21081                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21082                final long sharedLibraryToken =
21083                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21084                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21085                final boolean isJar = (libEntry.path != null);
21086                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21087                if (isJar) {
21088                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21089                } else {
21090                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21091                }
21092                proto.end(sharedLibraryToken);
21093            }
21094        }
21095    }
21096
21097    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21098        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21099        ipw.println();
21100        ipw.println("Dexopt state:");
21101        ipw.increaseIndent();
21102        Collection<PackageParser.Package> packages = null;
21103        if (packageName != null) {
21104            PackageParser.Package targetPackage = mPackages.get(packageName);
21105            if (targetPackage != null) {
21106                packages = Collections.singletonList(targetPackage);
21107            } else {
21108                ipw.println("Unable to find package: " + packageName);
21109                return;
21110            }
21111        } else {
21112            packages = mPackages.values();
21113        }
21114
21115        for (PackageParser.Package pkg : packages) {
21116            ipw.println("[" + pkg.packageName + "]");
21117            ipw.increaseIndent();
21118            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21119            ipw.decreaseIndent();
21120        }
21121    }
21122
21123    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21124        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21125        ipw.println();
21126        ipw.println("Compiler stats:");
21127        ipw.increaseIndent();
21128        Collection<PackageParser.Package> packages = null;
21129        if (packageName != null) {
21130            PackageParser.Package targetPackage = mPackages.get(packageName);
21131            if (targetPackage != null) {
21132                packages = Collections.singletonList(targetPackage);
21133            } else {
21134                ipw.println("Unable to find package: " + packageName);
21135                return;
21136            }
21137        } else {
21138            packages = mPackages.values();
21139        }
21140
21141        for (PackageParser.Package pkg : packages) {
21142            ipw.println("[" + pkg.packageName + "]");
21143            ipw.increaseIndent();
21144
21145            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21146            if (stats == null) {
21147                ipw.println("(No recorded stats)");
21148            } else {
21149                stats.dump(ipw);
21150            }
21151            ipw.decreaseIndent();
21152        }
21153    }
21154
21155    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21156        pw.println("Enabled overlay paths:");
21157        final int N = mEnabledOverlayPaths.size();
21158        for (int i = 0; i < N; i++) {
21159            final int userId = mEnabledOverlayPaths.keyAt(i);
21160            pw.println(String.format("    User %d:", userId));
21161            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21162                mEnabledOverlayPaths.valueAt(i);
21163            final int M = userSpecificOverlays.size();
21164            for (int j = 0; j < M; j++) {
21165                final String targetPackageName = userSpecificOverlays.keyAt(j);
21166                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21167                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21168            }
21169        }
21170    }
21171
21172    private String dumpDomainString(String packageName) {
21173        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21174                .getList();
21175        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21176
21177        ArraySet<String> result = new ArraySet<>();
21178        if (iviList.size() > 0) {
21179            for (IntentFilterVerificationInfo ivi : iviList) {
21180                for (String host : ivi.getDomains()) {
21181                    result.add(host);
21182                }
21183            }
21184        }
21185        if (filters != null && filters.size() > 0) {
21186            for (IntentFilter filter : filters) {
21187                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21188                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21189                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21190                    result.addAll(filter.getHostsList());
21191                }
21192            }
21193        }
21194
21195        StringBuilder sb = new StringBuilder(result.size() * 16);
21196        for (String domain : result) {
21197            if (sb.length() > 0) sb.append(" ");
21198            sb.append(domain);
21199        }
21200        return sb.toString();
21201    }
21202
21203    // ------- apps on sdcard specific code -------
21204    static final boolean DEBUG_SD_INSTALL = false;
21205
21206    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21207
21208    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21209
21210    private boolean mMediaMounted = false;
21211
21212    static String getEncryptKey() {
21213        try {
21214            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21215                    SD_ENCRYPTION_KEYSTORE_NAME);
21216            if (sdEncKey == null) {
21217                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21218                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21219                if (sdEncKey == null) {
21220                    Slog.e(TAG, "Failed to create encryption keys");
21221                    return null;
21222                }
21223            }
21224            return sdEncKey;
21225        } catch (NoSuchAlgorithmException nsae) {
21226            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21227            return null;
21228        } catch (IOException ioe) {
21229            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21230            return null;
21231        }
21232    }
21233
21234    /*
21235     * Update media status on PackageManager.
21236     */
21237    @Override
21238    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21239        int callingUid = Binder.getCallingUid();
21240        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21241            throw new SecurityException("Media status can only be updated by the system");
21242        }
21243        // reader; this apparently protects mMediaMounted, but should probably
21244        // be a different lock in that case.
21245        synchronized (mPackages) {
21246            Log.i(TAG, "Updating external media status from "
21247                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21248                    + (mediaStatus ? "mounted" : "unmounted"));
21249            if (DEBUG_SD_INSTALL)
21250                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21251                        + ", mMediaMounted=" + mMediaMounted);
21252            if (mediaStatus == mMediaMounted) {
21253                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21254                        : 0, -1);
21255                mHandler.sendMessage(msg);
21256                return;
21257            }
21258            mMediaMounted = mediaStatus;
21259        }
21260        // Queue up an async operation since the package installation may take a
21261        // little while.
21262        mHandler.post(new Runnable() {
21263            public void run() {
21264                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21265            }
21266        });
21267    }
21268
21269    /**
21270     * Called by StorageManagerService when the initial ASECs to scan are available.
21271     * Should block until all the ASEC containers are finished being scanned.
21272     */
21273    public void scanAvailableAsecs() {
21274        updateExternalMediaStatusInner(true, false, false);
21275    }
21276
21277    /*
21278     * Collect information of applications on external media, map them against
21279     * existing containers and update information based on current mount status.
21280     * Please note that we always have to report status if reportStatus has been
21281     * set to true especially when unloading packages.
21282     */
21283    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21284            boolean externalStorage) {
21285        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21286        int[] uidArr = EmptyArray.INT;
21287
21288        final String[] list = PackageHelper.getSecureContainerList();
21289        if (ArrayUtils.isEmpty(list)) {
21290            Log.i(TAG, "No secure containers found");
21291        } else {
21292            // Process list of secure containers and categorize them
21293            // as active or stale based on their package internal state.
21294
21295            // reader
21296            synchronized (mPackages) {
21297                for (String cid : list) {
21298                    // Leave stages untouched for now; installer service owns them
21299                    if (PackageInstallerService.isStageName(cid)) continue;
21300
21301                    if (DEBUG_SD_INSTALL)
21302                        Log.i(TAG, "Processing container " + cid);
21303                    String pkgName = getAsecPackageName(cid);
21304                    if (pkgName == null) {
21305                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21306                        continue;
21307                    }
21308                    if (DEBUG_SD_INSTALL)
21309                        Log.i(TAG, "Looking for pkg : " + pkgName);
21310
21311                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21312                    if (ps == null) {
21313                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21314                        continue;
21315                    }
21316
21317                    /*
21318                     * Skip packages that are not external if we're unmounting
21319                     * external storage.
21320                     */
21321                    if (externalStorage && !isMounted && !isExternal(ps)) {
21322                        continue;
21323                    }
21324
21325                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21326                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21327                    // The package status is changed only if the code path
21328                    // matches between settings and the container id.
21329                    if (ps.codePathString != null
21330                            && ps.codePathString.startsWith(args.getCodePath())) {
21331                        if (DEBUG_SD_INSTALL) {
21332                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21333                                    + " at code path: " + ps.codePathString);
21334                        }
21335
21336                        // We do have a valid package installed on sdcard
21337                        processCids.put(args, ps.codePathString);
21338                        final int uid = ps.appId;
21339                        if (uid != -1) {
21340                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21341                        }
21342                    } else {
21343                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21344                                + ps.codePathString);
21345                    }
21346                }
21347            }
21348
21349            Arrays.sort(uidArr);
21350        }
21351
21352        // Process packages with valid entries.
21353        if (isMounted) {
21354            if (DEBUG_SD_INSTALL)
21355                Log.i(TAG, "Loading packages");
21356            loadMediaPackages(processCids, uidArr, externalStorage);
21357            startCleaningPackages();
21358            mInstallerService.onSecureContainersAvailable();
21359        } else {
21360            if (DEBUG_SD_INSTALL)
21361                Log.i(TAG, "Unloading packages");
21362            unloadMediaPackages(processCids, uidArr, reportStatus);
21363        }
21364    }
21365
21366    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21367            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21368        final int size = infos.size();
21369        final String[] packageNames = new String[size];
21370        final int[] packageUids = new int[size];
21371        for (int i = 0; i < size; i++) {
21372            final ApplicationInfo info = infos.get(i);
21373            packageNames[i] = info.packageName;
21374            packageUids[i] = info.uid;
21375        }
21376        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21377                finishedReceiver);
21378    }
21379
21380    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21381            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21382        sendResourcesChangedBroadcast(mediaStatus, replacing,
21383                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21384    }
21385
21386    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21387            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21388        int size = pkgList.length;
21389        if (size > 0) {
21390            // Send broadcasts here
21391            Bundle extras = new Bundle();
21392            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21393            if (uidArr != null) {
21394                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21395            }
21396            if (replacing) {
21397                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21398            }
21399            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21400                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21401            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21402        }
21403    }
21404
21405   /*
21406     * Look at potentially valid container ids from processCids If package
21407     * information doesn't match the one on record or package scanning fails,
21408     * the cid is added to list of removeCids. We currently don't delete stale
21409     * containers.
21410     */
21411    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21412            boolean externalStorage) {
21413        ArrayList<String> pkgList = new ArrayList<String>();
21414        Set<AsecInstallArgs> keys = processCids.keySet();
21415
21416        for (AsecInstallArgs args : keys) {
21417            String codePath = processCids.get(args);
21418            if (DEBUG_SD_INSTALL)
21419                Log.i(TAG, "Loading container : " + args.cid);
21420            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21421            try {
21422                // Make sure there are no container errors first.
21423                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21424                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21425                            + " when installing from sdcard");
21426                    continue;
21427                }
21428                // Check code path here.
21429                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21430                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21431                            + " does not match one in settings " + codePath);
21432                    continue;
21433                }
21434                // Parse package
21435                int parseFlags = mDefParseFlags;
21436                if (args.isExternalAsec()) {
21437                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21438                }
21439                if (args.isFwdLocked()) {
21440                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21441                }
21442
21443                synchronized (mInstallLock) {
21444                    PackageParser.Package pkg = null;
21445                    try {
21446                        // Sadly we don't know the package name yet to freeze it
21447                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21448                                SCAN_IGNORE_FROZEN, 0, null);
21449                    } catch (PackageManagerException e) {
21450                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21451                    }
21452                    // Scan the package
21453                    if (pkg != null) {
21454                        /*
21455                         * TODO why is the lock being held? doPostInstall is
21456                         * called in other places without the lock. This needs
21457                         * to be straightened out.
21458                         */
21459                        // writer
21460                        synchronized (mPackages) {
21461                            retCode = PackageManager.INSTALL_SUCCEEDED;
21462                            pkgList.add(pkg.packageName);
21463                            // Post process args
21464                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21465                                    pkg.applicationInfo.uid);
21466                        }
21467                    } else {
21468                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21469                    }
21470                }
21471
21472            } finally {
21473                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21474                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21475                }
21476            }
21477        }
21478        // writer
21479        synchronized (mPackages) {
21480            // If the platform SDK has changed since the last time we booted,
21481            // we need to re-grant app permission to catch any new ones that
21482            // appear. This is really a hack, and means that apps can in some
21483            // cases get permissions that the user didn't initially explicitly
21484            // allow... it would be nice to have some better way to handle
21485            // this situation.
21486            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21487                    : mSettings.getInternalVersion();
21488            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21489                    : StorageManager.UUID_PRIVATE_INTERNAL;
21490
21491            int updateFlags = UPDATE_PERMISSIONS_ALL;
21492            if (ver.sdkVersion != mSdkVersion) {
21493                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21494                        + mSdkVersion + "; regranting permissions for external");
21495                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21496            }
21497            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21498
21499            // Yay, everything is now upgraded
21500            ver.forceCurrent();
21501
21502            // can downgrade to reader
21503            // Persist settings
21504            mSettings.writeLPr();
21505        }
21506        // Send a broadcast to let everyone know we are done processing
21507        if (pkgList.size() > 0) {
21508            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21509        }
21510    }
21511
21512   /*
21513     * Utility method to unload a list of specified containers
21514     */
21515    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21516        // Just unmount all valid containers.
21517        for (AsecInstallArgs arg : cidArgs) {
21518            synchronized (mInstallLock) {
21519                arg.doPostDeleteLI(false);
21520           }
21521       }
21522   }
21523
21524    /*
21525     * Unload packages mounted on external media. This involves deleting package
21526     * data from internal structures, sending broadcasts about disabled packages,
21527     * gc'ing to free up references, unmounting all secure containers
21528     * corresponding to packages on external media, and posting a
21529     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21530     * that we always have to post this message if status has been requested no
21531     * matter what.
21532     */
21533    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21534            final boolean reportStatus) {
21535        if (DEBUG_SD_INSTALL)
21536            Log.i(TAG, "unloading media packages");
21537        ArrayList<String> pkgList = new ArrayList<String>();
21538        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21539        final Set<AsecInstallArgs> keys = processCids.keySet();
21540        for (AsecInstallArgs args : keys) {
21541            String pkgName = args.getPackageName();
21542            if (DEBUG_SD_INSTALL)
21543                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21544            // Delete package internally
21545            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21546            synchronized (mInstallLock) {
21547                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21548                final boolean res;
21549                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21550                        "unloadMediaPackages")) {
21551                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21552                            null);
21553                }
21554                if (res) {
21555                    pkgList.add(pkgName);
21556                } else {
21557                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21558                    failedList.add(args);
21559                }
21560            }
21561        }
21562
21563        // reader
21564        synchronized (mPackages) {
21565            // We didn't update the settings after removing each package;
21566            // write them now for all packages.
21567            mSettings.writeLPr();
21568        }
21569
21570        // We have to absolutely send UPDATED_MEDIA_STATUS only
21571        // after confirming that all the receivers processed the ordered
21572        // broadcast when packages get disabled, force a gc to clean things up.
21573        // and unload all the containers.
21574        if (pkgList.size() > 0) {
21575            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21576                    new IIntentReceiver.Stub() {
21577                public void performReceive(Intent intent, int resultCode, String data,
21578                        Bundle extras, boolean ordered, boolean sticky,
21579                        int sendingUser) throws RemoteException {
21580                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21581                            reportStatus ? 1 : 0, 1, keys);
21582                    mHandler.sendMessage(msg);
21583                }
21584            });
21585        } else {
21586            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21587                    keys);
21588            mHandler.sendMessage(msg);
21589        }
21590    }
21591
21592    private void loadPrivatePackages(final VolumeInfo vol) {
21593        mHandler.post(new Runnable() {
21594            @Override
21595            public void run() {
21596                loadPrivatePackagesInner(vol);
21597            }
21598        });
21599    }
21600
21601    private void loadPrivatePackagesInner(VolumeInfo vol) {
21602        final String volumeUuid = vol.fsUuid;
21603        if (TextUtils.isEmpty(volumeUuid)) {
21604            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21605            return;
21606        }
21607
21608        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21609        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21610        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21611
21612        final VersionInfo ver;
21613        final List<PackageSetting> packages;
21614        synchronized (mPackages) {
21615            ver = mSettings.findOrCreateVersion(volumeUuid);
21616            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21617        }
21618
21619        for (PackageSetting ps : packages) {
21620            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21621            synchronized (mInstallLock) {
21622                final PackageParser.Package pkg;
21623                try {
21624                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21625                    loaded.add(pkg.applicationInfo);
21626
21627                } catch (PackageManagerException e) {
21628                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21629                }
21630
21631                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21632                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21633                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21634                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21635                }
21636            }
21637        }
21638
21639        // Reconcile app data for all started/unlocked users
21640        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21641        final UserManager um = mContext.getSystemService(UserManager.class);
21642        UserManagerInternal umInternal = getUserManagerInternal();
21643        for (UserInfo user : um.getUsers()) {
21644            final int flags;
21645            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21646                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21647            } else if (umInternal.isUserRunning(user.id)) {
21648                flags = StorageManager.FLAG_STORAGE_DE;
21649            } else {
21650                continue;
21651            }
21652
21653            try {
21654                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21655                synchronized (mInstallLock) {
21656                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21657                }
21658            } catch (IllegalStateException e) {
21659                // Device was probably ejected, and we'll process that event momentarily
21660                Slog.w(TAG, "Failed to prepare storage: " + e);
21661            }
21662        }
21663
21664        synchronized (mPackages) {
21665            int updateFlags = UPDATE_PERMISSIONS_ALL;
21666            if (ver.sdkVersion != mSdkVersion) {
21667                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21668                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21669                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21670            }
21671            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21672
21673            // Yay, everything is now upgraded
21674            ver.forceCurrent();
21675
21676            mSettings.writeLPr();
21677        }
21678
21679        for (PackageFreezer freezer : freezers) {
21680            freezer.close();
21681        }
21682
21683        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21684        sendResourcesChangedBroadcast(true, false, loaded, null);
21685    }
21686
21687    private void unloadPrivatePackages(final VolumeInfo vol) {
21688        mHandler.post(new Runnable() {
21689            @Override
21690            public void run() {
21691                unloadPrivatePackagesInner(vol);
21692            }
21693        });
21694    }
21695
21696    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21697        final String volumeUuid = vol.fsUuid;
21698        if (TextUtils.isEmpty(volumeUuid)) {
21699            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21700            return;
21701        }
21702
21703        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21704        synchronized (mInstallLock) {
21705        synchronized (mPackages) {
21706            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21707            for (PackageSetting ps : packages) {
21708                if (ps.pkg == null) continue;
21709
21710                final ApplicationInfo info = ps.pkg.applicationInfo;
21711                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21712                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21713
21714                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21715                        "unloadPrivatePackagesInner")) {
21716                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21717                            false, null)) {
21718                        unloaded.add(info);
21719                    } else {
21720                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21721                    }
21722                }
21723
21724                // Try very hard to release any references to this package
21725                // so we don't risk the system server being killed due to
21726                // open FDs
21727                AttributeCache.instance().removePackage(ps.name);
21728            }
21729
21730            mSettings.writeLPr();
21731        }
21732        }
21733
21734        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21735        sendResourcesChangedBroadcast(false, false, unloaded, null);
21736
21737        // Try very hard to release any references to this path so we don't risk
21738        // the system server being killed due to open FDs
21739        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21740
21741        for (int i = 0; i < 3; i++) {
21742            System.gc();
21743            System.runFinalization();
21744        }
21745    }
21746
21747    private void assertPackageKnown(String volumeUuid, String packageName)
21748            throws PackageManagerException {
21749        synchronized (mPackages) {
21750            // Normalize package name to handle renamed packages
21751            packageName = normalizePackageNameLPr(packageName);
21752
21753            final PackageSetting ps = mSettings.mPackages.get(packageName);
21754            if (ps == null) {
21755                throw new PackageManagerException("Package " + packageName + " is unknown");
21756            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21757                throw new PackageManagerException(
21758                        "Package " + packageName + " found on unknown volume " + volumeUuid
21759                                + "; expected volume " + ps.volumeUuid);
21760            }
21761        }
21762    }
21763
21764    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21765            throws PackageManagerException {
21766        synchronized (mPackages) {
21767            // Normalize package name to handle renamed packages
21768            packageName = normalizePackageNameLPr(packageName);
21769
21770            final PackageSetting ps = mSettings.mPackages.get(packageName);
21771            if (ps == null) {
21772                throw new PackageManagerException("Package " + packageName + " is unknown");
21773            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21774                throw new PackageManagerException(
21775                        "Package " + packageName + " found on unknown volume " + volumeUuid
21776                                + "; expected volume " + ps.volumeUuid);
21777            } else if (!ps.getInstalled(userId)) {
21778                throw new PackageManagerException(
21779                        "Package " + packageName + " not installed for user " + userId);
21780            }
21781        }
21782    }
21783
21784    private List<String> collectAbsoluteCodePaths() {
21785        synchronized (mPackages) {
21786            List<String> codePaths = new ArrayList<>();
21787            final int packageCount = mSettings.mPackages.size();
21788            for (int i = 0; i < packageCount; i++) {
21789                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21790                codePaths.add(ps.codePath.getAbsolutePath());
21791            }
21792            return codePaths;
21793        }
21794    }
21795
21796    /**
21797     * Examine all apps present on given mounted volume, and destroy apps that
21798     * aren't expected, either due to uninstallation or reinstallation on
21799     * another volume.
21800     */
21801    private void reconcileApps(String volumeUuid) {
21802        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21803        List<File> filesToDelete = null;
21804
21805        final File[] files = FileUtils.listFilesOrEmpty(
21806                Environment.getDataAppDirectory(volumeUuid));
21807        for (File file : files) {
21808            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21809                    && !PackageInstallerService.isStageName(file.getName());
21810            if (!isPackage) {
21811                // Ignore entries which are not packages
21812                continue;
21813            }
21814
21815            String absolutePath = file.getAbsolutePath();
21816
21817            boolean pathValid = false;
21818            final int absoluteCodePathCount = absoluteCodePaths.size();
21819            for (int i = 0; i < absoluteCodePathCount; i++) {
21820                String absoluteCodePath = absoluteCodePaths.get(i);
21821                if (absolutePath.startsWith(absoluteCodePath)) {
21822                    pathValid = true;
21823                    break;
21824                }
21825            }
21826
21827            if (!pathValid) {
21828                if (filesToDelete == null) {
21829                    filesToDelete = new ArrayList<>();
21830                }
21831                filesToDelete.add(file);
21832            }
21833        }
21834
21835        if (filesToDelete != null) {
21836            final int fileToDeleteCount = filesToDelete.size();
21837            for (int i = 0; i < fileToDeleteCount; i++) {
21838                File fileToDelete = filesToDelete.get(i);
21839                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21840                synchronized (mInstallLock) {
21841                    removeCodePathLI(fileToDelete);
21842                }
21843            }
21844        }
21845    }
21846
21847    /**
21848     * Reconcile all app data for the given user.
21849     * <p>
21850     * Verifies that directories exist and that ownership and labeling is
21851     * correct for all installed apps on all mounted volumes.
21852     */
21853    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21854        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21855        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21856            final String volumeUuid = vol.getFsUuid();
21857            synchronized (mInstallLock) {
21858                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21859            }
21860        }
21861    }
21862
21863    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21864            boolean migrateAppData) {
21865        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21866    }
21867
21868    /**
21869     * Reconcile all app data on given mounted volume.
21870     * <p>
21871     * Destroys app data that isn't expected, either due to uninstallation or
21872     * reinstallation on another volume.
21873     * <p>
21874     * Verifies that directories exist and that ownership and labeling is
21875     * correct for all installed apps.
21876     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21877     */
21878    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21879            boolean migrateAppData, boolean onlyCoreApps) {
21880        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21881                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21882        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21883
21884        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21885        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21886
21887        // First look for stale data that doesn't belong, and check if things
21888        // have changed since we did our last restorecon
21889        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21890            if (StorageManager.isFileEncryptedNativeOrEmulated()
21891                    && !StorageManager.isUserKeyUnlocked(userId)) {
21892                throw new RuntimeException(
21893                        "Yikes, someone asked us to reconcile CE storage while " + userId
21894                                + " was still locked; this would have caused massive data loss!");
21895            }
21896
21897            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21898            for (File file : files) {
21899                final String packageName = file.getName();
21900                try {
21901                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21902                } catch (PackageManagerException e) {
21903                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21904                    try {
21905                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21906                                StorageManager.FLAG_STORAGE_CE, 0);
21907                    } catch (InstallerException e2) {
21908                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21909                    }
21910                }
21911            }
21912        }
21913        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21914            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21915            for (File file : files) {
21916                final String packageName = file.getName();
21917                try {
21918                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21919                } catch (PackageManagerException e) {
21920                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21921                    try {
21922                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21923                                StorageManager.FLAG_STORAGE_DE, 0);
21924                    } catch (InstallerException e2) {
21925                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21926                    }
21927                }
21928            }
21929        }
21930
21931        // Ensure that data directories are ready to roll for all packages
21932        // installed for this volume and user
21933        final List<PackageSetting> packages;
21934        synchronized (mPackages) {
21935            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21936        }
21937        int preparedCount = 0;
21938        for (PackageSetting ps : packages) {
21939            final String packageName = ps.name;
21940            if (ps.pkg == null) {
21941                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21942                // TODO: might be due to legacy ASEC apps; we should circle back
21943                // and reconcile again once they're scanned
21944                continue;
21945            }
21946            // Skip non-core apps if requested
21947            if (onlyCoreApps && !ps.pkg.coreApp) {
21948                result.add(packageName);
21949                continue;
21950            }
21951
21952            if (ps.getInstalled(userId)) {
21953                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21954                preparedCount++;
21955            }
21956        }
21957
21958        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21959        return result;
21960    }
21961
21962    /**
21963     * Prepare app data for the given app just after it was installed or
21964     * upgraded. This method carefully only touches users that it's installed
21965     * for, and it forces a restorecon to handle any seinfo changes.
21966     * <p>
21967     * Verifies that directories exist and that ownership and labeling is
21968     * correct for all installed apps. If there is an ownership mismatch, it
21969     * will try recovering system apps by wiping data; third-party app data is
21970     * left intact.
21971     * <p>
21972     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21973     */
21974    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21975        final PackageSetting ps;
21976        synchronized (mPackages) {
21977            ps = mSettings.mPackages.get(pkg.packageName);
21978            mSettings.writeKernelMappingLPr(ps);
21979        }
21980
21981        final UserManager um = mContext.getSystemService(UserManager.class);
21982        UserManagerInternal umInternal = getUserManagerInternal();
21983        for (UserInfo user : um.getUsers()) {
21984            final int flags;
21985            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21986                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21987            } else if (umInternal.isUserRunning(user.id)) {
21988                flags = StorageManager.FLAG_STORAGE_DE;
21989            } else {
21990                continue;
21991            }
21992
21993            if (ps.getInstalled(user.id)) {
21994                // TODO: when user data is locked, mark that we're still dirty
21995                prepareAppDataLIF(pkg, user.id, flags);
21996            }
21997        }
21998    }
21999
22000    /**
22001     * Prepare app data for the given app.
22002     * <p>
22003     * Verifies that directories exist and that ownership and labeling is
22004     * correct for all installed apps. If there is an ownership mismatch, this
22005     * will try recovering system apps by wiping data; third-party app data is
22006     * left intact.
22007     */
22008    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22009        if (pkg == null) {
22010            Slog.wtf(TAG, "Package was null!", new Throwable());
22011            return;
22012        }
22013        prepareAppDataLeafLIF(pkg, userId, flags);
22014        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22015        for (int i = 0; i < childCount; i++) {
22016            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22017        }
22018    }
22019
22020    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22021            boolean maybeMigrateAppData) {
22022        prepareAppDataLIF(pkg, userId, flags);
22023
22024        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22025            // We may have just shuffled around app data directories, so
22026            // prepare them one more time
22027            prepareAppDataLIF(pkg, userId, flags);
22028        }
22029    }
22030
22031    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22032        if (DEBUG_APP_DATA) {
22033            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22034                    + Integer.toHexString(flags));
22035        }
22036
22037        final String volumeUuid = pkg.volumeUuid;
22038        final String packageName = pkg.packageName;
22039        final ApplicationInfo app = pkg.applicationInfo;
22040        final int appId = UserHandle.getAppId(app.uid);
22041
22042        Preconditions.checkNotNull(app.seInfo);
22043
22044        long ceDataInode = -1;
22045        try {
22046            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22047                    appId, app.seInfo, app.targetSdkVersion);
22048        } catch (InstallerException e) {
22049            if (app.isSystemApp()) {
22050                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22051                        + ", but trying to recover: " + e);
22052                destroyAppDataLeafLIF(pkg, userId, flags);
22053                try {
22054                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22055                            appId, app.seInfo, app.targetSdkVersion);
22056                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22057                } catch (InstallerException e2) {
22058                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22059                }
22060            } else {
22061                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22062            }
22063        }
22064
22065        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22066            // TODO: mark this structure as dirty so we persist it!
22067            synchronized (mPackages) {
22068                final PackageSetting ps = mSettings.mPackages.get(packageName);
22069                if (ps != null) {
22070                    ps.setCeDataInode(ceDataInode, userId);
22071                }
22072            }
22073        }
22074
22075        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22076    }
22077
22078    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22079        if (pkg == null) {
22080            Slog.wtf(TAG, "Package was null!", new Throwable());
22081            return;
22082        }
22083        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22084        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22085        for (int i = 0; i < childCount; i++) {
22086            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22087        }
22088    }
22089
22090    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22091        final String volumeUuid = pkg.volumeUuid;
22092        final String packageName = pkg.packageName;
22093        final ApplicationInfo app = pkg.applicationInfo;
22094
22095        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22096            // Create a native library symlink only if we have native libraries
22097            // and if the native libraries are 32 bit libraries. We do not provide
22098            // this symlink for 64 bit libraries.
22099            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22100                final String nativeLibPath = app.nativeLibraryDir;
22101                try {
22102                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22103                            nativeLibPath, userId);
22104                } catch (InstallerException e) {
22105                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22106                }
22107            }
22108        }
22109    }
22110
22111    /**
22112     * For system apps on non-FBE devices, this method migrates any existing
22113     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22114     * requested by the app.
22115     */
22116    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22117        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22118                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22119            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22120                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22121            try {
22122                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22123                        storageTarget);
22124            } catch (InstallerException e) {
22125                logCriticalInfo(Log.WARN,
22126                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22127            }
22128            return true;
22129        } else {
22130            return false;
22131        }
22132    }
22133
22134    public PackageFreezer freezePackage(String packageName, String killReason) {
22135        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22136    }
22137
22138    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22139        return new PackageFreezer(packageName, userId, killReason);
22140    }
22141
22142    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22143            String killReason) {
22144        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22145    }
22146
22147    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22148            String killReason) {
22149        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22150            return new PackageFreezer();
22151        } else {
22152            return freezePackage(packageName, userId, killReason);
22153        }
22154    }
22155
22156    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22157            String killReason) {
22158        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22159    }
22160
22161    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22162            String killReason) {
22163        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22164            return new PackageFreezer();
22165        } else {
22166            return freezePackage(packageName, userId, killReason);
22167        }
22168    }
22169
22170    /**
22171     * Class that freezes and kills the given package upon creation, and
22172     * unfreezes it upon closing. This is typically used when doing surgery on
22173     * app code/data to prevent the app from running while you're working.
22174     */
22175    private class PackageFreezer implements AutoCloseable {
22176        private final String mPackageName;
22177        private final PackageFreezer[] mChildren;
22178
22179        private final boolean mWeFroze;
22180
22181        private final AtomicBoolean mClosed = new AtomicBoolean();
22182        private final CloseGuard mCloseGuard = CloseGuard.get();
22183
22184        /**
22185         * Create and return a stub freezer that doesn't actually do anything,
22186         * typically used when someone requested
22187         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22188         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22189         */
22190        public PackageFreezer() {
22191            mPackageName = null;
22192            mChildren = null;
22193            mWeFroze = false;
22194            mCloseGuard.open("close");
22195        }
22196
22197        public PackageFreezer(String packageName, int userId, String killReason) {
22198            synchronized (mPackages) {
22199                mPackageName = packageName;
22200                mWeFroze = mFrozenPackages.add(mPackageName);
22201
22202                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22203                if (ps != null) {
22204                    killApplication(ps.name, ps.appId, userId, killReason);
22205                }
22206
22207                final PackageParser.Package p = mPackages.get(packageName);
22208                if (p != null && p.childPackages != null) {
22209                    final int N = p.childPackages.size();
22210                    mChildren = new PackageFreezer[N];
22211                    for (int i = 0; i < N; i++) {
22212                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22213                                userId, killReason);
22214                    }
22215                } else {
22216                    mChildren = null;
22217                }
22218            }
22219            mCloseGuard.open("close");
22220        }
22221
22222        @Override
22223        protected void finalize() throws Throwable {
22224            try {
22225                mCloseGuard.warnIfOpen();
22226                close();
22227            } finally {
22228                super.finalize();
22229            }
22230        }
22231
22232        @Override
22233        public void close() {
22234            mCloseGuard.close();
22235            if (mClosed.compareAndSet(false, true)) {
22236                synchronized (mPackages) {
22237                    if (mWeFroze) {
22238                        mFrozenPackages.remove(mPackageName);
22239                    }
22240
22241                    if (mChildren != null) {
22242                        for (PackageFreezer freezer : mChildren) {
22243                            freezer.close();
22244                        }
22245                    }
22246                }
22247            }
22248        }
22249    }
22250
22251    /**
22252     * Verify that given package is currently frozen.
22253     */
22254    private void checkPackageFrozen(String packageName) {
22255        synchronized (mPackages) {
22256            if (!mFrozenPackages.contains(packageName)) {
22257                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22258            }
22259        }
22260    }
22261
22262    @Override
22263    public int movePackage(final String packageName, final String volumeUuid) {
22264        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22265
22266        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22267        final int moveId = mNextMoveId.getAndIncrement();
22268        mHandler.post(new Runnable() {
22269            @Override
22270            public void run() {
22271                try {
22272                    movePackageInternal(packageName, volumeUuid, moveId, user);
22273                } catch (PackageManagerException e) {
22274                    Slog.w(TAG, "Failed to move " + packageName, e);
22275                    mMoveCallbacks.notifyStatusChanged(moveId,
22276                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22277                }
22278            }
22279        });
22280        return moveId;
22281    }
22282
22283    private void movePackageInternal(final String packageName, final String volumeUuid,
22284            final int moveId, UserHandle user) throws PackageManagerException {
22285        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22286        final PackageManager pm = mContext.getPackageManager();
22287
22288        final boolean currentAsec;
22289        final String currentVolumeUuid;
22290        final File codeFile;
22291        final String installerPackageName;
22292        final String packageAbiOverride;
22293        final int appId;
22294        final String seinfo;
22295        final String label;
22296        final int targetSdkVersion;
22297        final PackageFreezer freezer;
22298        final int[] installedUserIds;
22299
22300        // reader
22301        synchronized (mPackages) {
22302            final PackageParser.Package pkg = mPackages.get(packageName);
22303            final PackageSetting ps = mSettings.mPackages.get(packageName);
22304            if (pkg == null || ps == null) {
22305                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22306            }
22307
22308            if (pkg.applicationInfo.isSystemApp()) {
22309                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22310                        "Cannot move system application");
22311            }
22312
22313            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22314            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22315                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22316            if (isInternalStorage && !allow3rdPartyOnInternal) {
22317                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22318                        "3rd party apps are not allowed on internal storage");
22319            }
22320
22321            if (pkg.applicationInfo.isExternalAsec()) {
22322                currentAsec = true;
22323                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22324            } else if (pkg.applicationInfo.isForwardLocked()) {
22325                currentAsec = true;
22326                currentVolumeUuid = "forward_locked";
22327            } else {
22328                currentAsec = false;
22329                currentVolumeUuid = ps.volumeUuid;
22330
22331                final File probe = new File(pkg.codePath);
22332                final File probeOat = new File(probe, "oat");
22333                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22334                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22335                            "Move only supported for modern cluster style installs");
22336                }
22337            }
22338
22339            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22340                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22341                        "Package already moved to " + volumeUuid);
22342            }
22343            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22344                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22345                        "Device admin cannot be moved");
22346            }
22347
22348            if (mFrozenPackages.contains(packageName)) {
22349                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22350                        "Failed to move already frozen package");
22351            }
22352
22353            codeFile = new File(pkg.codePath);
22354            installerPackageName = ps.installerPackageName;
22355            packageAbiOverride = ps.cpuAbiOverrideString;
22356            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22357            seinfo = pkg.applicationInfo.seInfo;
22358            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22359            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22360            freezer = freezePackage(packageName, "movePackageInternal");
22361            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22362        }
22363
22364        final Bundle extras = new Bundle();
22365        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22366        extras.putString(Intent.EXTRA_TITLE, label);
22367        mMoveCallbacks.notifyCreated(moveId, extras);
22368
22369        int installFlags;
22370        final boolean moveCompleteApp;
22371        final File measurePath;
22372
22373        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22374            installFlags = INSTALL_INTERNAL;
22375            moveCompleteApp = !currentAsec;
22376            measurePath = Environment.getDataAppDirectory(volumeUuid);
22377        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22378            installFlags = INSTALL_EXTERNAL;
22379            moveCompleteApp = false;
22380            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22381        } else {
22382            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22383            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22384                    || !volume.isMountedWritable()) {
22385                freezer.close();
22386                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22387                        "Move location not mounted private volume");
22388            }
22389
22390            Preconditions.checkState(!currentAsec);
22391
22392            installFlags = INSTALL_INTERNAL;
22393            moveCompleteApp = true;
22394            measurePath = Environment.getDataAppDirectory(volumeUuid);
22395        }
22396
22397        final PackageStats stats = new PackageStats(null, -1);
22398        synchronized (mInstaller) {
22399            for (int userId : installedUserIds) {
22400                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22401                    freezer.close();
22402                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22403                            "Failed to measure package size");
22404                }
22405            }
22406        }
22407
22408        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22409                + stats.dataSize);
22410
22411        final long startFreeBytes = measurePath.getUsableSpace();
22412        final long sizeBytes;
22413        if (moveCompleteApp) {
22414            sizeBytes = stats.codeSize + stats.dataSize;
22415        } else {
22416            sizeBytes = stats.codeSize;
22417        }
22418
22419        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22420            freezer.close();
22421            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22422                    "Not enough free space to move");
22423        }
22424
22425        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22426
22427        final CountDownLatch installedLatch = new CountDownLatch(1);
22428        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22429            @Override
22430            public void onUserActionRequired(Intent intent) throws RemoteException {
22431                throw new IllegalStateException();
22432            }
22433
22434            @Override
22435            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22436                    Bundle extras) throws RemoteException {
22437                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22438                        + PackageManager.installStatusToString(returnCode, msg));
22439
22440                installedLatch.countDown();
22441                freezer.close();
22442
22443                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22444                switch (status) {
22445                    case PackageInstaller.STATUS_SUCCESS:
22446                        mMoveCallbacks.notifyStatusChanged(moveId,
22447                                PackageManager.MOVE_SUCCEEDED);
22448                        break;
22449                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22450                        mMoveCallbacks.notifyStatusChanged(moveId,
22451                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22452                        break;
22453                    default:
22454                        mMoveCallbacks.notifyStatusChanged(moveId,
22455                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22456                        break;
22457                }
22458            }
22459        };
22460
22461        final MoveInfo move;
22462        if (moveCompleteApp) {
22463            // Kick off a thread to report progress estimates
22464            new Thread() {
22465                @Override
22466                public void run() {
22467                    while (true) {
22468                        try {
22469                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22470                                break;
22471                            }
22472                        } catch (InterruptedException ignored) {
22473                        }
22474
22475                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22476                        final int progress = 10 + (int) MathUtils.constrain(
22477                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22478                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22479                    }
22480                }
22481            }.start();
22482
22483            final String dataAppName = codeFile.getName();
22484            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22485                    dataAppName, appId, seinfo, targetSdkVersion);
22486        } else {
22487            move = null;
22488        }
22489
22490        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22491
22492        final Message msg = mHandler.obtainMessage(INIT_COPY);
22493        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22494        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22495                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22496                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22497                PackageManager.INSTALL_REASON_UNKNOWN);
22498        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22499        msg.obj = params;
22500
22501        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22502                System.identityHashCode(msg.obj));
22503        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22504                System.identityHashCode(msg.obj));
22505
22506        mHandler.sendMessage(msg);
22507    }
22508
22509    @Override
22510    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22511        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22512
22513        final int realMoveId = mNextMoveId.getAndIncrement();
22514        final Bundle extras = new Bundle();
22515        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22516        mMoveCallbacks.notifyCreated(realMoveId, extras);
22517
22518        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22519            @Override
22520            public void onCreated(int moveId, Bundle extras) {
22521                // Ignored
22522            }
22523
22524            @Override
22525            public void onStatusChanged(int moveId, int status, long estMillis) {
22526                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22527            }
22528        };
22529
22530        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22531        storage.setPrimaryStorageUuid(volumeUuid, callback);
22532        return realMoveId;
22533    }
22534
22535    @Override
22536    public int getMoveStatus(int moveId) {
22537        mContext.enforceCallingOrSelfPermission(
22538                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22539        return mMoveCallbacks.mLastStatus.get(moveId);
22540    }
22541
22542    @Override
22543    public void registerMoveCallback(IPackageMoveObserver callback) {
22544        mContext.enforceCallingOrSelfPermission(
22545                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22546        mMoveCallbacks.register(callback);
22547    }
22548
22549    @Override
22550    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22551        mContext.enforceCallingOrSelfPermission(
22552                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22553        mMoveCallbacks.unregister(callback);
22554    }
22555
22556    @Override
22557    public boolean setInstallLocation(int loc) {
22558        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22559                null);
22560        if (getInstallLocation() == loc) {
22561            return true;
22562        }
22563        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22564                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22565            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22566                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22567            return true;
22568        }
22569        return false;
22570   }
22571
22572    @Override
22573    public int getInstallLocation() {
22574        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22575                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22576                PackageHelper.APP_INSTALL_AUTO);
22577    }
22578
22579    /** Called by UserManagerService */
22580    void cleanUpUser(UserManagerService userManager, int userHandle) {
22581        synchronized (mPackages) {
22582            mDirtyUsers.remove(userHandle);
22583            mUserNeedsBadging.delete(userHandle);
22584            mSettings.removeUserLPw(userHandle);
22585            mPendingBroadcasts.remove(userHandle);
22586            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22587            removeUnusedPackagesLPw(userManager, userHandle);
22588        }
22589    }
22590
22591    /**
22592     * We're removing userHandle and would like to remove any downloaded packages
22593     * that are no longer in use by any other user.
22594     * @param userHandle the user being removed
22595     */
22596    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22597        final boolean DEBUG_CLEAN_APKS = false;
22598        int [] users = userManager.getUserIds();
22599        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22600        while (psit.hasNext()) {
22601            PackageSetting ps = psit.next();
22602            if (ps.pkg == null) {
22603                continue;
22604            }
22605            final String packageName = ps.pkg.packageName;
22606            // Skip over if system app
22607            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22608                continue;
22609            }
22610            if (DEBUG_CLEAN_APKS) {
22611                Slog.i(TAG, "Checking package " + packageName);
22612            }
22613            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22614            if (keep) {
22615                if (DEBUG_CLEAN_APKS) {
22616                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22617                }
22618            } else {
22619                for (int i = 0; i < users.length; i++) {
22620                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22621                        keep = true;
22622                        if (DEBUG_CLEAN_APKS) {
22623                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22624                                    + users[i]);
22625                        }
22626                        break;
22627                    }
22628                }
22629            }
22630            if (!keep) {
22631                if (DEBUG_CLEAN_APKS) {
22632                    Slog.i(TAG, "  Removing package " + packageName);
22633                }
22634                mHandler.post(new Runnable() {
22635                    public void run() {
22636                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22637                                userHandle, 0);
22638                    } //end run
22639                });
22640            }
22641        }
22642    }
22643
22644    /** Called by UserManagerService */
22645    void createNewUser(int userId, String[] disallowedPackages) {
22646        synchronized (mInstallLock) {
22647            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22648        }
22649        synchronized (mPackages) {
22650            scheduleWritePackageRestrictionsLocked(userId);
22651            scheduleWritePackageListLocked(userId);
22652            applyFactoryDefaultBrowserLPw(userId);
22653            primeDomainVerificationsLPw(userId);
22654        }
22655    }
22656
22657    void onNewUserCreated(final int userId) {
22658        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22659        // If permission review for legacy apps is required, we represent
22660        // dagerous permissions for such apps as always granted runtime
22661        // permissions to keep per user flag state whether review is needed.
22662        // Hence, if a new user is added we have to propagate dangerous
22663        // permission grants for these legacy apps.
22664        if (mPermissionReviewRequired) {
22665            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22666                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22667        }
22668    }
22669
22670    @Override
22671    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22672        mContext.enforceCallingOrSelfPermission(
22673                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22674                "Only package verification agents can read the verifier device identity");
22675
22676        synchronized (mPackages) {
22677            return mSettings.getVerifierDeviceIdentityLPw();
22678        }
22679    }
22680
22681    @Override
22682    public void setPermissionEnforced(String permission, boolean enforced) {
22683        // TODO: Now that we no longer change GID for storage, this should to away.
22684        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22685                "setPermissionEnforced");
22686        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22687            synchronized (mPackages) {
22688                if (mSettings.mReadExternalStorageEnforced == null
22689                        || mSettings.mReadExternalStorageEnforced != enforced) {
22690                    mSettings.mReadExternalStorageEnforced = enforced;
22691                    mSettings.writeLPr();
22692                }
22693            }
22694            // kill any non-foreground processes so we restart them and
22695            // grant/revoke the GID.
22696            final IActivityManager am = ActivityManager.getService();
22697            if (am != null) {
22698                final long token = Binder.clearCallingIdentity();
22699                try {
22700                    am.killProcessesBelowForeground("setPermissionEnforcement");
22701                } catch (RemoteException e) {
22702                } finally {
22703                    Binder.restoreCallingIdentity(token);
22704                }
22705            }
22706        } else {
22707            throw new IllegalArgumentException("No selective enforcement for " + permission);
22708        }
22709    }
22710
22711    @Override
22712    @Deprecated
22713    public boolean isPermissionEnforced(String permission) {
22714        return true;
22715    }
22716
22717    @Override
22718    public boolean isStorageLow() {
22719        final long token = Binder.clearCallingIdentity();
22720        try {
22721            final DeviceStorageMonitorInternal
22722                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22723            if (dsm != null) {
22724                return dsm.isMemoryLow();
22725            } else {
22726                return false;
22727            }
22728        } finally {
22729            Binder.restoreCallingIdentity(token);
22730        }
22731    }
22732
22733    @Override
22734    public IPackageInstaller getPackageInstaller() {
22735        return mInstallerService;
22736    }
22737
22738    private boolean userNeedsBadging(int userId) {
22739        int index = mUserNeedsBadging.indexOfKey(userId);
22740        if (index < 0) {
22741            final UserInfo userInfo;
22742            final long token = Binder.clearCallingIdentity();
22743            try {
22744                userInfo = sUserManager.getUserInfo(userId);
22745            } finally {
22746                Binder.restoreCallingIdentity(token);
22747            }
22748            final boolean b;
22749            if (userInfo != null && userInfo.isManagedProfile()) {
22750                b = true;
22751            } else {
22752                b = false;
22753            }
22754            mUserNeedsBadging.put(userId, b);
22755            return b;
22756        }
22757        return mUserNeedsBadging.valueAt(index);
22758    }
22759
22760    @Override
22761    public KeySet getKeySetByAlias(String packageName, String alias) {
22762        if (packageName == null || alias == null) {
22763            return null;
22764        }
22765        synchronized(mPackages) {
22766            final PackageParser.Package pkg = mPackages.get(packageName);
22767            if (pkg == null) {
22768                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22769                throw new IllegalArgumentException("Unknown package: " + packageName);
22770            }
22771            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22772            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22773        }
22774    }
22775
22776    @Override
22777    public KeySet getSigningKeySet(String packageName) {
22778        if (packageName == null) {
22779            return null;
22780        }
22781        synchronized(mPackages) {
22782            final PackageParser.Package pkg = mPackages.get(packageName);
22783            if (pkg == null) {
22784                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22785                throw new IllegalArgumentException("Unknown package: " + packageName);
22786            }
22787            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22788                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22789                throw new SecurityException("May not access signing KeySet of other apps.");
22790            }
22791            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22792            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22793        }
22794    }
22795
22796    @Override
22797    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22798        if (packageName == null || ks == null) {
22799            return false;
22800        }
22801        synchronized(mPackages) {
22802            final PackageParser.Package pkg = mPackages.get(packageName);
22803            if (pkg == null) {
22804                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22805                throw new IllegalArgumentException("Unknown package: " + packageName);
22806            }
22807            IBinder ksh = ks.getToken();
22808            if (ksh instanceof KeySetHandle) {
22809                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22810                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22811            }
22812            return false;
22813        }
22814    }
22815
22816    @Override
22817    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22818        if (packageName == null || ks == null) {
22819            return false;
22820        }
22821        synchronized(mPackages) {
22822            final PackageParser.Package pkg = mPackages.get(packageName);
22823            if (pkg == null) {
22824                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22825                throw new IllegalArgumentException("Unknown package: " + packageName);
22826            }
22827            IBinder ksh = ks.getToken();
22828            if (ksh instanceof KeySetHandle) {
22829                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22830                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22831            }
22832            return false;
22833        }
22834    }
22835
22836    private void deletePackageIfUnusedLPr(final String packageName) {
22837        PackageSetting ps = mSettings.mPackages.get(packageName);
22838        if (ps == null) {
22839            return;
22840        }
22841        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22842            // TODO Implement atomic delete if package is unused
22843            // It is currently possible that the package will be deleted even if it is installed
22844            // after this method returns.
22845            mHandler.post(new Runnable() {
22846                public void run() {
22847                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22848                            0, PackageManager.DELETE_ALL_USERS);
22849                }
22850            });
22851        }
22852    }
22853
22854    /**
22855     * Check and throw if the given before/after packages would be considered a
22856     * downgrade.
22857     */
22858    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22859            throws PackageManagerException {
22860        if (after.versionCode < before.mVersionCode) {
22861            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22862                    "Update version code " + after.versionCode + " is older than current "
22863                    + before.mVersionCode);
22864        } else if (after.versionCode == before.mVersionCode) {
22865            if (after.baseRevisionCode < before.baseRevisionCode) {
22866                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22867                        "Update base revision code " + after.baseRevisionCode
22868                        + " is older than current " + before.baseRevisionCode);
22869            }
22870
22871            if (!ArrayUtils.isEmpty(after.splitNames)) {
22872                for (int i = 0; i < after.splitNames.length; i++) {
22873                    final String splitName = after.splitNames[i];
22874                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22875                    if (j != -1) {
22876                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22877                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22878                                    "Update split " + splitName + " revision code "
22879                                    + after.splitRevisionCodes[i] + " is older than current "
22880                                    + before.splitRevisionCodes[j]);
22881                        }
22882                    }
22883                }
22884            }
22885        }
22886    }
22887
22888    private static class MoveCallbacks extends Handler {
22889        private static final int MSG_CREATED = 1;
22890        private static final int MSG_STATUS_CHANGED = 2;
22891
22892        private final RemoteCallbackList<IPackageMoveObserver>
22893                mCallbacks = new RemoteCallbackList<>();
22894
22895        private final SparseIntArray mLastStatus = new SparseIntArray();
22896
22897        public MoveCallbacks(Looper looper) {
22898            super(looper);
22899        }
22900
22901        public void register(IPackageMoveObserver callback) {
22902            mCallbacks.register(callback);
22903        }
22904
22905        public void unregister(IPackageMoveObserver callback) {
22906            mCallbacks.unregister(callback);
22907        }
22908
22909        @Override
22910        public void handleMessage(Message msg) {
22911            final SomeArgs args = (SomeArgs) msg.obj;
22912            final int n = mCallbacks.beginBroadcast();
22913            for (int i = 0; i < n; i++) {
22914                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22915                try {
22916                    invokeCallback(callback, msg.what, args);
22917                } catch (RemoteException ignored) {
22918                }
22919            }
22920            mCallbacks.finishBroadcast();
22921            args.recycle();
22922        }
22923
22924        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22925                throws RemoteException {
22926            switch (what) {
22927                case MSG_CREATED: {
22928                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22929                    break;
22930                }
22931                case MSG_STATUS_CHANGED: {
22932                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22933                    break;
22934                }
22935            }
22936        }
22937
22938        private void notifyCreated(int moveId, Bundle extras) {
22939            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22940
22941            final SomeArgs args = SomeArgs.obtain();
22942            args.argi1 = moveId;
22943            args.arg2 = extras;
22944            obtainMessage(MSG_CREATED, args).sendToTarget();
22945        }
22946
22947        private void notifyStatusChanged(int moveId, int status) {
22948            notifyStatusChanged(moveId, status, -1);
22949        }
22950
22951        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22952            Slog.v(TAG, "Move " + moveId + " status " + status);
22953
22954            final SomeArgs args = SomeArgs.obtain();
22955            args.argi1 = moveId;
22956            args.argi2 = status;
22957            args.arg3 = estMillis;
22958            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22959
22960            synchronized (mLastStatus) {
22961                mLastStatus.put(moveId, status);
22962            }
22963        }
22964    }
22965
22966    private final static class OnPermissionChangeListeners extends Handler {
22967        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22968
22969        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22970                new RemoteCallbackList<>();
22971
22972        public OnPermissionChangeListeners(Looper looper) {
22973            super(looper);
22974        }
22975
22976        @Override
22977        public void handleMessage(Message msg) {
22978            switch (msg.what) {
22979                case MSG_ON_PERMISSIONS_CHANGED: {
22980                    final int uid = msg.arg1;
22981                    handleOnPermissionsChanged(uid);
22982                } break;
22983            }
22984        }
22985
22986        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22987            mPermissionListeners.register(listener);
22988
22989        }
22990
22991        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22992            mPermissionListeners.unregister(listener);
22993        }
22994
22995        public void onPermissionsChanged(int uid) {
22996            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22997                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22998            }
22999        }
23000
23001        private void handleOnPermissionsChanged(int uid) {
23002            final int count = mPermissionListeners.beginBroadcast();
23003            try {
23004                for (int i = 0; i < count; i++) {
23005                    IOnPermissionsChangeListener callback = mPermissionListeners
23006                            .getBroadcastItem(i);
23007                    try {
23008                        callback.onPermissionsChanged(uid);
23009                    } catch (RemoteException e) {
23010                        Log.e(TAG, "Permission listener is dead", e);
23011                    }
23012                }
23013            } finally {
23014                mPermissionListeners.finishBroadcast();
23015            }
23016        }
23017    }
23018
23019    private class PackageManagerInternalImpl extends PackageManagerInternal {
23020        @Override
23021        public void setLocationPackagesProvider(PackagesProvider provider) {
23022            synchronized (mPackages) {
23023                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23024            }
23025        }
23026
23027        @Override
23028        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23029            synchronized (mPackages) {
23030                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23031            }
23032        }
23033
23034        @Override
23035        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23036            synchronized (mPackages) {
23037                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23038            }
23039        }
23040
23041        @Override
23042        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23043            synchronized (mPackages) {
23044                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23045            }
23046        }
23047
23048        @Override
23049        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23050            synchronized (mPackages) {
23051                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23052            }
23053        }
23054
23055        @Override
23056        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23057            synchronized (mPackages) {
23058                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23059            }
23060        }
23061
23062        @Override
23063        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23064            synchronized (mPackages) {
23065                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23066                        packageName, userId);
23067            }
23068        }
23069
23070        @Override
23071        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23072            synchronized (mPackages) {
23073                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23074                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23075                        packageName, userId);
23076            }
23077        }
23078
23079        @Override
23080        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23081            synchronized (mPackages) {
23082                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23083                        packageName, userId);
23084            }
23085        }
23086
23087        @Override
23088        public void setKeepUninstalledPackages(final List<String> packageList) {
23089            Preconditions.checkNotNull(packageList);
23090            List<String> removedFromList = null;
23091            synchronized (mPackages) {
23092                if (mKeepUninstalledPackages != null) {
23093                    final int packagesCount = mKeepUninstalledPackages.size();
23094                    for (int i = 0; i < packagesCount; i++) {
23095                        String oldPackage = mKeepUninstalledPackages.get(i);
23096                        if (packageList != null && packageList.contains(oldPackage)) {
23097                            continue;
23098                        }
23099                        if (removedFromList == null) {
23100                            removedFromList = new ArrayList<>();
23101                        }
23102                        removedFromList.add(oldPackage);
23103                    }
23104                }
23105                mKeepUninstalledPackages = new ArrayList<>(packageList);
23106                if (removedFromList != null) {
23107                    final int removedCount = removedFromList.size();
23108                    for (int i = 0; i < removedCount; i++) {
23109                        deletePackageIfUnusedLPr(removedFromList.get(i));
23110                    }
23111                }
23112            }
23113        }
23114
23115        @Override
23116        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23117            synchronized (mPackages) {
23118                // If we do not support permission review, done.
23119                if (!mPermissionReviewRequired) {
23120                    return false;
23121                }
23122
23123                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23124                if (packageSetting == null) {
23125                    return false;
23126                }
23127
23128                // Permission review applies only to apps not supporting the new permission model.
23129                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23130                    return false;
23131                }
23132
23133                // Legacy apps have the permission and get user consent on launch.
23134                PermissionsState permissionsState = packageSetting.getPermissionsState();
23135                return permissionsState.isPermissionReviewRequired(userId);
23136            }
23137        }
23138
23139        @Override
23140        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23141            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23142        }
23143
23144        @Override
23145        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23146                int userId) {
23147            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23148        }
23149
23150        @Override
23151        public void setDeviceAndProfileOwnerPackages(
23152                int deviceOwnerUserId, String deviceOwnerPackage,
23153                SparseArray<String> profileOwnerPackages) {
23154            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23155                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23156        }
23157
23158        @Override
23159        public boolean isPackageDataProtected(int userId, String packageName) {
23160            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23161        }
23162
23163        @Override
23164        public boolean isPackageEphemeral(int userId, String packageName) {
23165            synchronized (mPackages) {
23166                final PackageSetting ps = mSettings.mPackages.get(packageName);
23167                return ps != null ? ps.getInstantApp(userId) : false;
23168            }
23169        }
23170
23171        @Override
23172        public boolean wasPackageEverLaunched(String packageName, int userId) {
23173            synchronized (mPackages) {
23174                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23175            }
23176        }
23177
23178        @Override
23179        public void grantRuntimePermission(String packageName, String name, int userId,
23180                boolean overridePolicy) {
23181            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23182                    overridePolicy);
23183        }
23184
23185        @Override
23186        public void revokeRuntimePermission(String packageName, String name, int userId,
23187                boolean overridePolicy) {
23188            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23189                    overridePolicy);
23190        }
23191
23192        @Override
23193        public String getNameForUid(int uid) {
23194            return PackageManagerService.this.getNameForUid(uid);
23195        }
23196
23197        @Override
23198        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23199                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23200            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23201                    responseObj, origIntent, resolvedType, callingPackage, userId);
23202        }
23203
23204        @Override
23205        public void grantEphemeralAccess(int userId, Intent intent,
23206                int targetAppId, int ephemeralAppId) {
23207            synchronized (mPackages) {
23208                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23209                        targetAppId, ephemeralAppId);
23210            }
23211        }
23212
23213        @Override
23214        public boolean isInstantAppInstallerComponent(ComponentName component) {
23215            synchronized (mPackages) {
23216                return component != null && component.equals(mInstantAppInstallerComponent);
23217            }
23218        }
23219
23220        @Override
23221        public void pruneInstantApps() {
23222            synchronized (mPackages) {
23223                mInstantAppRegistry.pruneInstantAppsLPw();
23224            }
23225        }
23226
23227        @Override
23228        public String getSetupWizardPackageName() {
23229            return mSetupWizardPackage;
23230        }
23231
23232        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23233            if (policy != null) {
23234                mExternalSourcesPolicy = policy;
23235            }
23236        }
23237
23238        @Override
23239        public boolean isPackagePersistent(String packageName) {
23240            synchronized (mPackages) {
23241                PackageParser.Package pkg = mPackages.get(packageName);
23242                return pkg != null
23243                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23244                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23245                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23246                        : false;
23247            }
23248        }
23249
23250        @Override
23251        public List<PackageInfo> getOverlayPackages(int userId) {
23252            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23253            synchronized (mPackages) {
23254                for (PackageParser.Package p : mPackages.values()) {
23255                    if (p.mOverlayTarget != null) {
23256                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23257                        if (pkg != null) {
23258                            overlayPackages.add(pkg);
23259                        }
23260                    }
23261                }
23262            }
23263            return overlayPackages;
23264        }
23265
23266        @Override
23267        public List<String> getTargetPackageNames(int userId) {
23268            List<String> targetPackages = new ArrayList<>();
23269            synchronized (mPackages) {
23270                for (PackageParser.Package p : mPackages.values()) {
23271                    if (p.mOverlayTarget == null) {
23272                        targetPackages.add(p.packageName);
23273                    }
23274                }
23275            }
23276            return targetPackages;
23277        }
23278
23279        @Override
23280        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23281                @Nullable List<String> overlayPackageNames) {
23282            synchronized (mPackages) {
23283                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23284                    Slog.e(TAG, "failed to find package " + targetPackageName);
23285                    return false;
23286                }
23287
23288                ArrayList<String> paths = null;
23289                if (overlayPackageNames != null) {
23290                    final int N = overlayPackageNames.size();
23291                    paths = new ArrayList<>(N);
23292                    for (int i = 0; i < N; i++) {
23293                        final String packageName = overlayPackageNames.get(i);
23294                        final PackageParser.Package pkg = mPackages.get(packageName);
23295                        if (pkg == null) {
23296                            Slog.e(TAG, "failed to find package " + packageName);
23297                            return false;
23298                        }
23299                        paths.add(pkg.baseCodePath);
23300                    }
23301                }
23302
23303                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23304                    mEnabledOverlayPaths.get(userId);
23305                if (userSpecificOverlays == null) {
23306                    userSpecificOverlays = new ArrayMap<>();
23307                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23308                }
23309
23310                if (paths != null && paths.size() > 0) {
23311                    userSpecificOverlays.put(targetPackageName, paths);
23312                } else {
23313                    userSpecificOverlays.remove(targetPackageName);
23314                }
23315                return true;
23316            }
23317        }
23318
23319        @Override
23320        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23321                int flags, int userId) {
23322            return resolveIntentInternal(
23323                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23324        }
23325
23326        @Override
23327        public ResolveInfo resolveService(Intent intent, String resolvedType,
23328                int flags, int userId, int callingUid) {
23329            return resolveServiceInternal(
23330                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23331        }
23332
23333
23334        @Override
23335        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23336            synchronized (mPackages) {
23337                mIsolatedOwners.put(isolatedUid, ownerUid);
23338            }
23339        }
23340
23341        @Override
23342        public void removeIsolatedUid(int isolatedUid) {
23343            synchronized (mPackages) {
23344                mIsolatedOwners.delete(isolatedUid);
23345            }
23346        }
23347    }
23348
23349    @Override
23350    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23351        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23352        synchronized (mPackages) {
23353            final long identity = Binder.clearCallingIdentity();
23354            try {
23355                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23356                        packageNames, userId);
23357            } finally {
23358                Binder.restoreCallingIdentity(identity);
23359            }
23360        }
23361    }
23362
23363    @Override
23364    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23365        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23366        synchronized (mPackages) {
23367            final long identity = Binder.clearCallingIdentity();
23368            try {
23369                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23370                        packageNames, userId);
23371            } finally {
23372                Binder.restoreCallingIdentity(identity);
23373            }
23374        }
23375    }
23376
23377    private static void enforceSystemOrPhoneCaller(String tag) {
23378        int callingUid = Binder.getCallingUid();
23379        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23380            throw new SecurityException(
23381                    "Cannot call " + tag + " from UID " + callingUid);
23382        }
23383    }
23384
23385    boolean isHistoricalPackageUsageAvailable() {
23386        return mPackageUsage.isHistoricalPackageUsageAvailable();
23387    }
23388
23389    /**
23390     * Return a <b>copy</b> of the collection of packages known to the package manager.
23391     * @return A copy of the values of mPackages.
23392     */
23393    Collection<PackageParser.Package> getPackages() {
23394        synchronized (mPackages) {
23395            return new ArrayList<>(mPackages.values());
23396        }
23397    }
23398
23399    /**
23400     * Logs process start information (including base APK hash) to the security log.
23401     * @hide
23402     */
23403    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23404            String apkFile, int pid) {
23405        if (!SecurityLog.isLoggingEnabled()) {
23406            return;
23407        }
23408        Bundle data = new Bundle();
23409        data.putLong("startTimestamp", System.currentTimeMillis());
23410        data.putString("processName", processName);
23411        data.putInt("uid", uid);
23412        data.putString("seinfo", seinfo);
23413        data.putString("apkFile", apkFile);
23414        data.putInt("pid", pid);
23415        Message msg = mProcessLoggingHandler.obtainMessage(
23416                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23417        msg.setData(data);
23418        mProcessLoggingHandler.sendMessage(msg);
23419    }
23420
23421    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23422        return mCompilerStats.getPackageStats(pkgName);
23423    }
23424
23425    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23426        return getOrCreateCompilerPackageStats(pkg.packageName);
23427    }
23428
23429    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23430        return mCompilerStats.getOrCreatePackageStats(pkgName);
23431    }
23432
23433    public void deleteCompilerPackageStats(String pkgName) {
23434        mCompilerStats.deletePackageStats(pkgName);
23435    }
23436
23437    @Override
23438    public int getInstallReason(String packageName, int userId) {
23439        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23440                true /* requireFullPermission */, false /* checkShell */,
23441                "get install reason");
23442        synchronized (mPackages) {
23443            final PackageSetting ps = mSettings.mPackages.get(packageName);
23444            if (ps != null) {
23445                return ps.getInstallReason(userId);
23446            }
23447        }
23448        return PackageManager.INSTALL_REASON_UNKNOWN;
23449    }
23450
23451    @Override
23452    public boolean canRequestPackageInstalls(String packageName, int userId) {
23453        int callingUid = Binder.getCallingUid();
23454        int uid = getPackageUid(packageName, 0, userId);
23455        if (callingUid != uid && callingUid != Process.ROOT_UID
23456                && callingUid != Process.SYSTEM_UID) {
23457            throw new SecurityException(
23458                    "Caller uid " + callingUid + " does not own package " + packageName);
23459        }
23460        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23461        if (info == null) {
23462            return false;
23463        }
23464        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23465            throw new UnsupportedOperationException(
23466                    "Operation only supported on apps targeting Android O or higher");
23467        }
23468        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23469        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23470        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23471            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23472        }
23473        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23474            return false;
23475        }
23476        if (mExternalSourcesPolicy != null) {
23477            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23478            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23479                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23480            }
23481        }
23482        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23483    }
23484
23485    @Override
23486    public ComponentName getInstantAppResolverSettingsComponent() {
23487        return mInstantAppResolverSettingsComponent;
23488    }
23489}
23490