PackageManagerService.java revision 6df866a8510af2776c48425a361f708ae7f5d7d6
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_NUMBER,
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    @GuardedBy("mPackages")
612    private boolean mDexOptDialogShown;
613
614    /** The location for ASEC container files on internal storage. */
615    final String mAsecInternalPath;
616
617    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
618    // LOCK HELD.  Can be called with mInstallLock held.
619    @GuardedBy("mInstallLock")
620    final Installer mInstaller;
621
622    /** Directory where installed third-party apps stored */
623    final File mAppInstallDir;
624
625    /**
626     * Directory to which applications installed internally have their
627     * 32 bit native libraries copied.
628     */
629    private File mAppLib32InstallDir;
630
631    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
632    // apps.
633    final File mDrmAppPrivateInstallDir;
634
635    // ----------------------------------------------------------------
636
637    // Lock for state used when installing and doing other long running
638    // operations.  Methods that must be called with this lock held have
639    // the suffix "LI".
640    final Object mInstallLock = new Object();
641
642    // ----------------------------------------------------------------
643
644    // Keys are String (package name), values are Package.  This also serves
645    // as the lock for the global state.  Methods that must be called with
646    // this lock held have the prefix "LP".
647    @GuardedBy("mPackages")
648    final ArrayMap<String, PackageParser.Package> mPackages =
649            new ArrayMap<String, PackageParser.Package>();
650
651    final ArrayMap<String, Set<String>> mKnownCodebase =
652            new ArrayMap<String, Set<String>>();
653
654    // Keys are isolated uids and values are the uid of the application
655    // that created the isolated proccess.
656    @GuardedBy("mPackages")
657    final SparseIntArray mIsolatedOwners = new SparseIntArray();
658
659    // List of APK paths to load for each user and package. This data is never
660    // persisted by the package manager. Instead, the overlay manager will
661    // ensure the data is up-to-date in runtime.
662    @GuardedBy("mPackages")
663    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
664        new SparseArray<ArrayMap<String, ArrayList<String>>>();
665
666    /**
667     * Tracks new system packages [received in an OTA] that we expect to
668     * find updated user-installed versions. Keys are package name, values
669     * are package location.
670     */
671    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
672    /**
673     * Tracks high priority intent filters for protected actions. During boot, certain
674     * filter actions are protected and should never be allowed to have a high priority
675     * intent filter for them. However, there is one, and only one exception -- the
676     * setup wizard. It must be able to define a high priority intent filter for these
677     * actions to ensure there are no escapes from the wizard. We need to delay processing
678     * of these during boot as we need to look at all of the system packages in order
679     * to know which component is the setup wizard.
680     */
681    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
682    /**
683     * Whether or not processing protected filters should be deferred.
684     */
685    private boolean mDeferProtectedFilters = true;
686
687    /**
688     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
689     */
690    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
691    /**
692     * Whether or not system app permissions should be promoted from install to runtime.
693     */
694    boolean mPromoteSystemApps;
695
696    @GuardedBy("mPackages")
697    final Settings mSettings;
698
699    /**
700     * Set of package names that are currently "frozen", which means active
701     * surgery is being done on the code/data for that package. The platform
702     * will refuse to launch frozen packages to avoid race conditions.
703     *
704     * @see PackageFreezer
705     */
706    @GuardedBy("mPackages")
707    final ArraySet<String> mFrozenPackages = new ArraySet<>();
708
709    final ProtectedPackages mProtectedPackages;
710
711    boolean mFirstBoot;
712
713    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
714
715    // System configuration read by SystemConfig.
716    final int[] mGlobalGids;
717    final SparseArray<ArraySet<String>> mSystemPermissions;
718    @GuardedBy("mAvailableFeatures")
719    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
720
721    // If mac_permissions.xml was found for seinfo labeling.
722    boolean mFoundPolicyFile;
723
724    private final InstantAppRegistry mInstantAppRegistry;
725
726    @GuardedBy("mPackages")
727    int mChangedPackagesSequenceNumber;
728    /**
729     * List of changed [installed, removed or updated] packages.
730     * mapping from user id -> sequence number -> package name
731     */
732    @GuardedBy("mPackages")
733    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
734    /**
735     * The sequence number of the last change to a package.
736     * mapping from user id -> package name -> sequence number
737     */
738    @GuardedBy("mPackages")
739    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
740
741    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
742        @Override public boolean hasFeature(String feature) {
743            return PackageManagerService.this.hasSystemFeature(feature, 0);
744        }
745    };
746
747    public static final class SharedLibraryEntry {
748        public final String path;
749        public final String apk;
750        public final SharedLibraryInfo info;
751
752        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
753                String declaringPackageName, int declaringPackageVersionCode) {
754            path = _path;
755            apk = _apk;
756            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
757                    declaringPackageName, declaringPackageVersionCode), null);
758        }
759    }
760
761    // Currently known shared libraries.
762    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
763    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
764            new ArrayMap<>();
765
766    // All available activities, for your resolving pleasure.
767    final ActivityIntentResolver mActivities =
768            new ActivityIntentResolver();
769
770    // All available receivers, for your resolving pleasure.
771    final ActivityIntentResolver mReceivers =
772            new ActivityIntentResolver();
773
774    // All available services, for your resolving pleasure.
775    final ServiceIntentResolver mServices = new ServiceIntentResolver();
776
777    // All available providers, for your resolving pleasure.
778    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
779
780    // Mapping from provider base names (first directory in content URI codePath)
781    // to the provider information.
782    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
783            new ArrayMap<String, PackageParser.Provider>();
784
785    // Mapping from instrumentation class names to info about them.
786    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
787            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
788
789    // Mapping from permission names to info about them.
790    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
791            new ArrayMap<String, PackageParser.PermissionGroup>();
792
793    // Packages whose data we have transfered into another package, thus
794    // should no longer exist.
795    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
796
797    // Broadcast actions that are only available to the system.
798    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
799
800    /** List of packages waiting for verification. */
801    final SparseArray<PackageVerificationState> mPendingVerification
802            = new SparseArray<PackageVerificationState>();
803
804    /** Set of packages associated with each app op permission. */
805    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
806
807    final PackageInstallerService mInstallerService;
808
809    private final PackageDexOptimizer mPackageDexOptimizer;
810    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
811    // is used by other apps).
812    private final DexManager mDexManager;
813
814    private AtomicInteger mNextMoveId = new AtomicInteger();
815    private final MoveCallbacks mMoveCallbacks;
816
817    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
818
819    // Cache of users who need badging.
820    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
821
822    /** Token for keys in mPendingVerification. */
823    private int mPendingVerificationToken = 0;
824
825    volatile boolean mSystemReady;
826    volatile boolean mSafeMode;
827    volatile boolean mHasSystemUidErrors;
828
829    ApplicationInfo mAndroidApplication;
830    final ActivityInfo mResolveActivity = new ActivityInfo();
831    final ResolveInfo mResolveInfo = new ResolveInfo();
832    ComponentName mResolveComponentName;
833    PackageParser.Package mPlatformPackage;
834    ComponentName mCustomResolverComponentName;
835
836    boolean mResolverReplaced = false;
837
838    private final @Nullable ComponentName mIntentFilterVerifierComponent;
839    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
840
841    private int mIntentFilterVerificationToken = 0;
842
843    /** The service connection to the ephemeral resolver */
844    final EphemeralResolverConnection mInstantAppResolverConnection;
845
846    /** Component used to install ephemeral applications */
847    ComponentName mInstantAppInstallerComponent;
848    /** Component used to show resolver settings for Instant Apps */
849    ComponentName mInstantAppResolverSettingsComponent;
850    ActivityInfo mInstantAppInstallerActivity;
851    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
852
853    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
854            = new SparseArray<IntentFilterVerificationState>();
855
856    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
857
858    // List of packages names to keep cached, even if they are uninstalled for all users
859    private List<String> mKeepUninstalledPackages;
860
861    private UserManagerInternal mUserManagerInternal;
862
863    private DeviceIdleController.LocalService mDeviceIdleController;
864
865    private File mCacheDir;
866
867    private ArraySet<String> mPrivappPermissionsViolations;
868
869    private Future<?> mPrepareAppDataFuture;
870
871    private static class IFVerificationParams {
872        PackageParser.Package pkg;
873        boolean replacing;
874        int userId;
875        int verifierUid;
876
877        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
878                int _userId, int _verifierUid) {
879            pkg = _pkg;
880            replacing = _replacing;
881            userId = _userId;
882            replacing = _replacing;
883            verifierUid = _verifierUid;
884        }
885    }
886
887    private interface IntentFilterVerifier<T extends IntentFilter> {
888        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
889                                               T filter, String packageName);
890        void startVerifications(int userId);
891        void receiveVerificationResponse(int verificationId);
892    }
893
894    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
895        private Context mContext;
896        private ComponentName mIntentFilterVerifierComponent;
897        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
898
899        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
900            mContext = context;
901            mIntentFilterVerifierComponent = verifierComponent;
902        }
903
904        private String getDefaultScheme() {
905            return IntentFilter.SCHEME_HTTPS;
906        }
907
908        @Override
909        public void startVerifications(int userId) {
910            // Launch verifications requests
911            int count = mCurrentIntentFilterVerifications.size();
912            for (int n=0; n<count; n++) {
913                int verificationId = mCurrentIntentFilterVerifications.get(n);
914                final IntentFilterVerificationState ivs =
915                        mIntentFilterVerificationStates.get(verificationId);
916
917                String packageName = ivs.getPackageName();
918
919                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
920                final int filterCount = filters.size();
921                ArraySet<String> domainsSet = new ArraySet<>();
922                for (int m=0; m<filterCount; m++) {
923                    PackageParser.ActivityIntentInfo filter = filters.get(m);
924                    domainsSet.addAll(filter.getHostsList());
925                }
926                synchronized (mPackages) {
927                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
928                            packageName, domainsSet) != null) {
929                        scheduleWriteSettingsLocked();
930                    }
931                }
932                sendVerificationRequest(userId, verificationId, ivs);
933            }
934            mCurrentIntentFilterVerifications.clear();
935        }
936
937        private void sendVerificationRequest(int userId, int verificationId,
938                IntentFilterVerificationState ivs) {
939
940            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
943                    verificationId);
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
946                    getDefaultScheme());
947            verificationIntent.putExtra(
948                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
949                    ivs.getHostsString());
950            verificationIntent.putExtra(
951                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
952                    ivs.getPackageName());
953            verificationIntent.setComponent(mIntentFilterVerifierComponent);
954            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
955
956            UserHandle user = new UserHandle(userId);
957            mContext.sendBroadcastAsUser(verificationIntent, user);
958            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
959                    "Sending IntentFilter verification broadcast");
960        }
961
962        public void receiveVerificationResponse(int verificationId) {
963            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
964
965            final boolean verified = ivs.isVerified();
966
967            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
968            final int count = filters.size();
969            if (DEBUG_DOMAIN_VERIFICATION) {
970                Slog.i(TAG, "Received verification response " + verificationId
971                        + " for " + count + " filters, verified=" + verified);
972            }
973            for (int n=0; n<count; n++) {
974                PackageParser.ActivityIntentInfo filter = filters.get(n);
975                filter.setVerified(verified);
976
977                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
978                        + " verified with result:" + verified + " and hosts:"
979                        + ivs.getHostsString());
980            }
981
982            mIntentFilterVerificationStates.remove(verificationId);
983
984            final String packageName = ivs.getPackageName();
985            IntentFilterVerificationInfo ivi = null;
986
987            synchronized (mPackages) {
988                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
989            }
990            if (ivi == null) {
991                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
992                        + verificationId + " packageName:" + packageName);
993                return;
994            }
995            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
996                    "Updating IntentFilterVerificationInfo for package " + packageName
997                            +" verificationId:" + verificationId);
998
999            synchronized (mPackages) {
1000                if (verified) {
1001                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1002                } else {
1003                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1004                }
1005                scheduleWriteSettingsLocked();
1006
1007                final int userId = ivs.getUserId();
1008                if (userId != UserHandle.USER_ALL) {
1009                    final int userStatus =
1010                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1011
1012                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1013                    boolean needUpdate = false;
1014
1015                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1016                    // already been set by the User thru the Disambiguation dialog
1017                    switch (userStatus) {
1018                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1019                            if (verified) {
1020                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1021                            } else {
1022                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1023                            }
1024                            needUpdate = true;
1025                            break;
1026
1027                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1028                            if (verified) {
1029                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1030                                needUpdate = true;
1031                            }
1032                            break;
1033
1034                        default:
1035                            // Nothing to do
1036                    }
1037
1038                    if (needUpdate) {
1039                        mSettings.updateIntentFilterVerificationStatusLPw(
1040                                packageName, updatedStatus, userId);
1041                        scheduleWritePackageRestrictionsLocked(userId);
1042                    }
1043                }
1044            }
1045        }
1046
1047        @Override
1048        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1049                    ActivityIntentInfo filter, String packageName) {
1050            if (!hasValidDomains(filter)) {
1051                return false;
1052            }
1053            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1054            if (ivs == null) {
1055                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1056                        packageName);
1057            }
1058            if (DEBUG_DOMAIN_VERIFICATION) {
1059                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1060            }
1061            ivs.addFilter(filter);
1062            return true;
1063        }
1064
1065        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1066                int userId, int verificationId, String packageName) {
1067            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1068                    verifierUid, userId, packageName);
1069            ivs.setPendingState();
1070            synchronized (mPackages) {
1071                mIntentFilterVerificationStates.append(verificationId, ivs);
1072                mCurrentIntentFilterVerifications.add(verificationId);
1073            }
1074            return ivs;
1075        }
1076    }
1077
1078    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1079        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1080                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1081                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1082    }
1083
1084    // Set of pending broadcasts for aggregating enable/disable of components.
1085    static class PendingPackageBroadcasts {
1086        // for each user id, a map of <package name -> components within that package>
1087        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1088
1089        public PendingPackageBroadcasts() {
1090            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1091        }
1092
1093        public ArrayList<String> get(int userId, String packageName) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            return packages.get(packageName);
1096        }
1097
1098        public void put(int userId, String packageName, ArrayList<String> components) {
1099            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1100            packages.put(packageName, components);
1101        }
1102
1103        public void remove(int userId, String packageName) {
1104            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1105            if (packages != null) {
1106                packages.remove(packageName);
1107            }
1108        }
1109
1110        public void remove(int userId) {
1111            mUidMap.remove(userId);
1112        }
1113
1114        public int userIdCount() {
1115            return mUidMap.size();
1116        }
1117
1118        public int userIdAt(int n) {
1119            return mUidMap.keyAt(n);
1120        }
1121
1122        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1123            return mUidMap.get(userId);
1124        }
1125
1126        public int size() {
1127            // total number of pending broadcast entries across all userIds
1128            int num = 0;
1129            for (int i = 0; i< mUidMap.size(); i++) {
1130                num += mUidMap.valueAt(i).size();
1131            }
1132            return num;
1133        }
1134
1135        public void clear() {
1136            mUidMap.clear();
1137        }
1138
1139        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1140            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1141            if (map == null) {
1142                map = new ArrayMap<String, ArrayList<String>>();
1143                mUidMap.put(userId, map);
1144            }
1145            return map;
1146        }
1147    }
1148    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1149
1150    // Service Connection to remote media container service to copy
1151    // package uri's from external media onto secure containers
1152    // or internal storage.
1153    private IMediaContainerService mContainerService = null;
1154
1155    static final int SEND_PENDING_BROADCAST = 1;
1156    static final int MCS_BOUND = 3;
1157    static final int END_COPY = 4;
1158    static final int INIT_COPY = 5;
1159    static final int MCS_UNBIND = 6;
1160    static final int START_CLEANING_PACKAGE = 7;
1161    static final int FIND_INSTALL_LOC = 8;
1162    static final int POST_INSTALL = 9;
1163    static final int MCS_RECONNECT = 10;
1164    static final int MCS_GIVE_UP = 11;
1165    static final int UPDATED_MEDIA_STATUS = 12;
1166    static final int WRITE_SETTINGS = 13;
1167    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1168    static final int PACKAGE_VERIFIED = 15;
1169    static final int CHECK_PENDING_VERIFICATION = 16;
1170    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1171    static final int INTENT_FILTER_VERIFIED = 18;
1172    static final int WRITE_PACKAGE_LIST = 19;
1173    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1174
1175    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1176
1177    // Delay time in millisecs
1178    static final int BROADCAST_DELAY = 10 * 1000;
1179
1180    static UserManagerService sUserManager;
1181
1182    // Stores a list of users whose package restrictions file needs to be updated
1183    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1184
1185    static final long DEFAULT_CONTAINER_WHITELIST_DURATION = 10 * 60 * 1000;
1186    final private DefaultContainerConnection mDefContainerConn =
1187            new DefaultContainerConnection();
1188    class DefaultContainerConnection implements ServiceConnection {
1189        public void onServiceConnected(ComponentName name, IBinder service) {
1190            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1191            final IMediaContainerService imcs = IMediaContainerService.Stub
1192                    .asInterface(Binder.allowBlocking(service));
1193            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1194        }
1195
1196        public void onServiceDisconnected(ComponentName name) {
1197            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1198        }
1199    }
1200
1201    // Recordkeeping of restore-after-install operations that are currently in flight
1202    // between the Package Manager and the Backup Manager
1203    static class PostInstallData {
1204        public InstallArgs args;
1205        public PackageInstalledInfo res;
1206
1207        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1208            args = _a;
1209            res = _r;
1210        }
1211    }
1212
1213    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1214    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1215
1216    // XML tags for backup/restore of various bits of state
1217    private static final String TAG_PREFERRED_BACKUP = "pa";
1218    private static final String TAG_DEFAULT_APPS = "da";
1219    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1220
1221    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1222    private static final String TAG_ALL_GRANTS = "rt-grants";
1223    private static final String TAG_GRANT = "grant";
1224    private static final String ATTR_PACKAGE_NAME = "pkg";
1225
1226    private static final String TAG_PERMISSION = "perm";
1227    private static final String ATTR_PERMISSION_NAME = "name";
1228    private static final String ATTR_IS_GRANTED = "g";
1229    private static final String ATTR_USER_SET = "set";
1230    private static final String ATTR_USER_FIXED = "fixed";
1231    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1232
1233    // System/policy permission grants are not backed up
1234    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_POLICY_FIXED
1236            | FLAG_PERMISSION_SYSTEM_FIXED
1237            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1238
1239    // And we back up these user-adjusted states
1240    private static final int USER_RUNTIME_GRANT_MASK =
1241            FLAG_PERMISSION_USER_SET
1242            | FLAG_PERMISSION_USER_FIXED
1243            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1244
1245    final @Nullable String mRequiredVerifierPackage;
1246    final @NonNull String mRequiredInstallerPackage;
1247    final @NonNull String mRequiredUninstallerPackage;
1248    final @Nullable String mSetupWizardPackage;
1249    final @Nullable String mStorageManagerPackage;
1250    final @NonNull String mServicesSystemSharedLibraryPackageName;
1251    final @NonNull String mSharedSystemSharedLibraryPackageName;
1252
1253    final boolean mPermissionReviewRequired;
1254
1255    private final PackageUsage mPackageUsage = new PackageUsage();
1256    private final CompilerStats mCompilerStats = new CompilerStats();
1257
1258    class PackageHandler extends Handler {
1259        private boolean mBound = false;
1260        final ArrayList<HandlerParams> mPendingInstalls =
1261            new ArrayList<HandlerParams>();
1262
1263        private boolean connectToService() {
1264            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1265                    " DefaultContainerService");
1266            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1267            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1268            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1269                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1270                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1271                mBound = true;
1272                return true;
1273            }
1274            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1275            return false;
1276        }
1277
1278        private void disconnectService() {
1279            mContainerService = null;
1280            mBound = false;
1281            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1282            mContext.unbindService(mDefContainerConn);
1283            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1284        }
1285
1286        PackageHandler(Looper looper) {
1287            super(looper);
1288        }
1289
1290        public void handleMessage(Message msg) {
1291            try {
1292                doHandleMessage(msg);
1293            } finally {
1294                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1295            }
1296        }
1297
1298        void doHandleMessage(Message msg) {
1299            switch (msg.what) {
1300                case INIT_COPY: {
1301                    HandlerParams params = (HandlerParams) msg.obj;
1302                    int idx = mPendingInstalls.size();
1303                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1304                    // If a bind was already initiated we dont really
1305                    // need to do anything. The pending install
1306                    // will be processed later on.
1307                    if (!mBound) {
1308                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                System.identityHashCode(mHandler));
1310                        // If this is the only one pending we might
1311                        // have to bind to the service again.
1312                        if (!connectToService()) {
1313                            Slog.e(TAG, "Failed to bind to media container service");
1314                            params.serviceError();
1315                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1316                                    System.identityHashCode(mHandler));
1317                            if (params.traceMethod != null) {
1318                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1319                                        params.traceCookie);
1320                            }
1321                            return;
1322                        } else {
1323                            // Once we bind to the service, the first
1324                            // pending request will be processed.
1325                            mPendingInstalls.add(idx, params);
1326                        }
1327                    } else {
1328                        mPendingInstalls.add(idx, params);
1329                        // Already bound to the service. Just make
1330                        // sure we trigger off processing the first request.
1331                        if (idx == 0) {
1332                            mHandler.sendEmptyMessage(MCS_BOUND);
1333                        }
1334                    }
1335                    break;
1336                }
1337                case MCS_BOUND: {
1338                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1339                    if (msg.obj != null) {
1340                        mContainerService = (IMediaContainerService) msg.obj;
1341                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1342                                System.identityHashCode(mHandler));
1343                    }
1344                    if (mContainerService == null) {
1345                        if (!mBound) {
1346                            // Something seriously wrong since we are not bound and we are not
1347                            // waiting for connection. Bail out.
1348                            Slog.e(TAG, "Cannot bind to media container service");
1349                            for (HandlerParams params : mPendingInstalls) {
1350                                // Indicate service bind error
1351                                params.serviceError();
1352                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1353                                        System.identityHashCode(params));
1354                                if (params.traceMethod != null) {
1355                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1356                                            params.traceMethod, params.traceCookie);
1357                                }
1358                                return;
1359                            }
1360                            mPendingInstalls.clear();
1361                        } else {
1362                            Slog.w(TAG, "Waiting to connect to media container service");
1363                        }
1364                    } else if (mPendingInstalls.size() > 0) {
1365                        HandlerParams params = mPendingInstalls.get(0);
1366                        if (params != null) {
1367                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1368                                    System.identityHashCode(params));
1369                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1370                            if (params.startCopy()) {
1371                                // We are done...  look for more work or to
1372                                // go idle.
1373                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1374                                        "Checking for more work or unbind...");
1375                                // Delete pending install
1376                                if (mPendingInstalls.size() > 0) {
1377                                    mPendingInstalls.remove(0);
1378                                }
1379                                if (mPendingInstalls.size() == 0) {
1380                                    if (mBound) {
1381                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1382                                                "Posting delayed MCS_UNBIND");
1383                                        removeMessages(MCS_UNBIND);
1384                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1385                                        // Unbind after a little delay, to avoid
1386                                        // continual thrashing.
1387                                        sendMessageDelayed(ubmsg, 10000);
1388                                    }
1389                                } else {
1390                                    // There are more pending requests in queue.
1391                                    // Just post MCS_BOUND message to trigger processing
1392                                    // of next pending install.
1393                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1394                                            "Posting MCS_BOUND for next work");
1395                                    mHandler.sendEmptyMessage(MCS_BOUND);
1396                                }
1397                            }
1398                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1399                        }
1400                    } else {
1401                        // Should never happen ideally.
1402                        Slog.w(TAG, "Empty queue");
1403                    }
1404                    break;
1405                }
1406                case MCS_RECONNECT: {
1407                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1408                    if (mPendingInstalls.size() > 0) {
1409                        if (mBound) {
1410                            disconnectService();
1411                        }
1412                        if (!connectToService()) {
1413                            Slog.e(TAG, "Failed to bind to media container service");
1414                            for (HandlerParams params : mPendingInstalls) {
1415                                // Indicate service bind error
1416                                params.serviceError();
1417                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1418                                        System.identityHashCode(params));
1419                            }
1420                            mPendingInstalls.clear();
1421                        }
1422                    }
1423                    break;
1424                }
1425                case MCS_UNBIND: {
1426                    // If there is no actual work left, then time to unbind.
1427                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1428
1429                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1430                        if (mBound) {
1431                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1432
1433                            disconnectService();
1434                        }
1435                    } else if (mPendingInstalls.size() > 0) {
1436                        // There are more pending requests in queue.
1437                        // Just post MCS_BOUND message to trigger processing
1438                        // of next pending install.
1439                        mHandler.sendEmptyMessage(MCS_BOUND);
1440                    }
1441
1442                    break;
1443                }
1444                case MCS_GIVE_UP: {
1445                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1446                    HandlerParams params = mPendingInstalls.remove(0);
1447                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1448                            System.identityHashCode(params));
1449                    break;
1450                }
1451                case SEND_PENDING_BROADCAST: {
1452                    String packages[];
1453                    ArrayList<String> components[];
1454                    int size = 0;
1455                    int uids[];
1456                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1457                    synchronized (mPackages) {
1458                        if (mPendingBroadcasts == null) {
1459                            return;
1460                        }
1461                        size = mPendingBroadcasts.size();
1462                        if (size <= 0) {
1463                            // Nothing to be done. Just return
1464                            return;
1465                        }
1466                        packages = new String[size];
1467                        components = new ArrayList[size];
1468                        uids = new int[size];
1469                        int i = 0;  // filling out the above arrays
1470
1471                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1472                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1473                            Iterator<Map.Entry<String, ArrayList<String>>> it
1474                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1475                                            .entrySet().iterator();
1476                            while (it.hasNext() && i < size) {
1477                                Map.Entry<String, ArrayList<String>> ent = it.next();
1478                                packages[i] = ent.getKey();
1479                                components[i] = ent.getValue();
1480                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1481                                uids[i] = (ps != null)
1482                                        ? UserHandle.getUid(packageUserId, ps.appId)
1483                                        : -1;
1484                                i++;
1485                            }
1486                        }
1487                        size = i;
1488                        mPendingBroadcasts.clear();
1489                    }
1490                    // Send broadcasts
1491                    for (int i = 0; i < size; i++) {
1492                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                    break;
1496                }
1497                case START_CLEANING_PACKAGE: {
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499                    final String packageName = (String)msg.obj;
1500                    final int userId = msg.arg1;
1501                    final boolean andCode = msg.arg2 != 0;
1502                    synchronized (mPackages) {
1503                        if (userId == UserHandle.USER_ALL) {
1504                            int[] users = sUserManager.getUserIds();
1505                            for (int user : users) {
1506                                mSettings.addPackageToCleanLPw(
1507                                        new PackageCleanItem(user, packageName, andCode));
1508                            }
1509                        } else {
1510                            mSettings.addPackageToCleanLPw(
1511                                    new PackageCleanItem(userId, packageName, andCode));
1512                        }
1513                    }
1514                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1515                    startCleaningPackages();
1516                } break;
1517                case POST_INSTALL: {
1518                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1519
1520                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1521                    final boolean didRestore = (msg.arg2 != 0);
1522                    mRunningInstalls.delete(msg.arg1);
1523
1524                    if (data != null) {
1525                        InstallArgs args = data.args;
1526                        PackageInstalledInfo parentRes = data.res;
1527
1528                        final boolean grantPermissions = (args.installFlags
1529                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1530                        final boolean killApp = (args.installFlags
1531                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1532                        final String[] grantedPermissions = args.installGrantPermissions;
1533
1534                        // Handle the parent package
1535                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1536                                grantedPermissions, didRestore, args.installerPackageName,
1537                                args.observer);
1538
1539                        // Handle the child packages
1540                        final int childCount = (parentRes.addedChildPackages != null)
1541                                ? parentRes.addedChildPackages.size() : 0;
1542                        for (int i = 0; i < childCount; i++) {
1543                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1544                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1545                                    grantedPermissions, false, args.installerPackageName,
1546                                    args.observer);
1547                        }
1548
1549                        // Log tracing if needed
1550                        if (args.traceMethod != null) {
1551                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1552                                    args.traceCookie);
1553                        }
1554                    } else {
1555                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1556                    }
1557
1558                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1559                } break;
1560                case UPDATED_MEDIA_STATUS: {
1561                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1562                    boolean reportStatus = msg.arg1 == 1;
1563                    boolean doGc = msg.arg2 == 1;
1564                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1565                    if (doGc) {
1566                        // Force a gc to clear up stale containers.
1567                        Runtime.getRuntime().gc();
1568                    }
1569                    if (msg.obj != null) {
1570                        @SuppressWarnings("unchecked")
1571                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1572                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1573                        // Unload containers
1574                        unloadAllContainers(args);
1575                    }
1576                    if (reportStatus) {
1577                        try {
1578                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1579                                    "Invoking StorageManagerService call back");
1580                            PackageHelper.getStorageManager().finishMediaUpdate();
1581                        } catch (RemoteException e) {
1582                            Log.e(TAG, "StorageManagerService not running?");
1583                        }
1584                    }
1585                } break;
1586                case WRITE_SETTINGS: {
1587                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1588                    synchronized (mPackages) {
1589                        removeMessages(WRITE_SETTINGS);
1590                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1591                        mSettings.writeLPr();
1592                        mDirtyUsers.clear();
1593                    }
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1595                } break;
1596                case WRITE_PACKAGE_RESTRICTIONS: {
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1600                        for (int userId : mDirtyUsers) {
1601                            mSettings.writePackageRestrictionsLPr(userId);
1602                        }
1603                        mDirtyUsers.clear();
1604                    }
1605                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1606                } break;
1607                case WRITE_PACKAGE_LIST: {
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1609                    synchronized (mPackages) {
1610                        removeMessages(WRITE_PACKAGE_LIST);
1611                        mSettings.writePackageListLPr(msg.arg1);
1612                    }
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614                } break;
1615                case CHECK_PENDING_VERIFICATION: {
1616                    final int verificationId = msg.arg1;
1617                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1618
1619                    if ((state != null) && !state.timeoutExtended()) {
1620                        final InstallArgs args = state.getInstallArgs();
1621                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1622
1623                        Slog.i(TAG, "Verification timed out for " + originUri);
1624                        mPendingVerification.remove(verificationId);
1625
1626                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1627
1628                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1629                            Slog.i(TAG, "Continuing with installation of " + originUri);
1630                            state.setVerifierResponse(Binder.getCallingUid(),
1631                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1632                            broadcastPackageVerified(verificationId, originUri,
1633                                    PackageManager.VERIFICATION_ALLOW,
1634                                    state.getInstallArgs().getUser());
1635                            try {
1636                                ret = args.copyApk(mContainerService, true);
1637                            } catch (RemoteException e) {
1638                                Slog.e(TAG, "Could not contact the ContainerService");
1639                            }
1640                        } else {
1641                            broadcastPackageVerified(verificationId, originUri,
1642                                    PackageManager.VERIFICATION_REJECT,
1643                                    state.getInstallArgs().getUser());
1644                        }
1645
1646                        Trace.asyncTraceEnd(
1647                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1648
1649                        processPendingInstall(args, ret);
1650                        mHandler.sendEmptyMessage(MCS_UNBIND);
1651                    }
1652                    break;
1653                }
1654                case PACKAGE_VERIFIED: {
1655                    final int verificationId = msg.arg1;
1656
1657                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1658                    if (state == null) {
1659                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1660                        break;
1661                    }
1662
1663                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1664
1665                    state.setVerifierResponse(response.callerUid, response.code);
1666
1667                    if (state.isVerificationComplete()) {
1668                        mPendingVerification.remove(verificationId);
1669
1670                        final InstallArgs args = state.getInstallArgs();
1671                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1672
1673                        int ret;
1674                        if (state.isInstallAllowed()) {
1675                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1676                            broadcastPackageVerified(verificationId, originUri,
1677                                    response.code, state.getInstallArgs().getUser());
1678                            try {
1679                                ret = args.copyApk(mContainerService, true);
1680                            } catch (RemoteException e) {
1681                                Slog.e(TAG, "Could not contact the ContainerService");
1682                            }
1683                        } else {
1684                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1685                        }
1686
1687                        Trace.asyncTraceEnd(
1688                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1689
1690                        processPendingInstall(args, ret);
1691                        mHandler.sendEmptyMessage(MCS_UNBIND);
1692                    }
1693
1694                    break;
1695                }
1696                case START_INTENT_FILTER_VERIFICATIONS: {
1697                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1698                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1699                            params.replacing, params.pkg);
1700                    break;
1701                }
1702                case INTENT_FILTER_VERIFIED: {
1703                    final int verificationId = msg.arg1;
1704
1705                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1706                            verificationId);
1707                    if (state == null) {
1708                        Slog.w(TAG, "Invalid IntentFilter verification token "
1709                                + verificationId + " received");
1710                        break;
1711                    }
1712
1713                    final int userId = state.getUserId();
1714
1715                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1716                            "Processing IntentFilter verification with token:"
1717                            + verificationId + " and userId:" + userId);
1718
1719                    final IntentFilterVerificationResponse response =
1720                            (IntentFilterVerificationResponse) msg.obj;
1721
1722                    state.setVerifierResponse(response.callerUid, response.code);
1723
1724                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1725                            "IntentFilter verification with token:" + verificationId
1726                            + " and userId:" + userId
1727                            + " is settings verifier response with response code:"
1728                            + response.code);
1729
1730                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1731                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1732                                + response.getFailedDomainsString());
1733                    }
1734
1735                    if (state.isVerificationComplete()) {
1736                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1737                    } else {
1738                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1739                                "IntentFilter verification with token:" + verificationId
1740                                + " was not said to be complete");
1741                    }
1742
1743                    break;
1744                }
1745                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1746                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1747                            mInstantAppResolverConnection,
1748                            (InstantAppRequest) msg.obj,
1749                            mInstantAppInstallerActivity,
1750                            mHandler);
1751                }
1752            }
1753        }
1754    }
1755
1756    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1757            boolean killApp, String[] grantedPermissions,
1758            boolean launchedForRestore, String installerPackage,
1759            IPackageInstallObserver2 installObserver) {
1760        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1761            // Send the removed broadcasts
1762            if (res.removedInfo != null) {
1763                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1764            }
1765
1766            // Now that we successfully installed the package, grant runtime
1767            // permissions if requested before broadcasting the install. Also
1768            // for legacy apps in permission review mode we clear the permission
1769            // review flag which is used to emulate runtime permissions for
1770            // legacy apps.
1771            if (grantPermissions) {
1772                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1773            }
1774
1775            final boolean update = res.removedInfo != null
1776                    && res.removedInfo.removedPackage != null;
1777
1778            // If this is the first time we have child packages for a disabled privileged
1779            // app that had no children, we grant requested runtime permissions to the new
1780            // children if the parent on the system image had them already granted.
1781            if (res.pkg.parentPackage != null) {
1782                synchronized (mPackages) {
1783                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1784                }
1785            }
1786
1787            synchronized (mPackages) {
1788                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1789            }
1790
1791            final String packageName = res.pkg.applicationInfo.packageName;
1792
1793            // Determine the set of users who are adding this package for
1794            // the first time vs. those who are seeing an update.
1795            int[] firstUsers = EMPTY_INT_ARRAY;
1796            int[] updateUsers = EMPTY_INT_ARRAY;
1797            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1798            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1799            for (int newUser : res.newUsers) {
1800                if (ps.getInstantApp(newUser)) {
1801                    continue;
1802                }
1803                if (allNewUsers) {
1804                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1805                    continue;
1806                }
1807                boolean isNew = true;
1808                for (int origUser : res.origUsers) {
1809                    if (origUser == newUser) {
1810                        isNew = false;
1811                        break;
1812                    }
1813                }
1814                if (isNew) {
1815                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1816                } else {
1817                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1818                }
1819            }
1820
1821            // Send installed broadcasts if the package is not a static shared lib.
1822            if (res.pkg.staticSharedLibName == null) {
1823                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1824
1825                // Send added for users that see the package for the first time
1826                // sendPackageAddedForNewUsers also deals with system apps
1827                int appId = UserHandle.getAppId(res.uid);
1828                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1829                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1830
1831                // Send added for users that don't see the package for the first time
1832                Bundle extras = new Bundle(1);
1833                extras.putInt(Intent.EXTRA_UID, res.uid);
1834                if (update) {
1835                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1836                }
1837                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1838                        extras, 0 /*flags*/, null /*targetPackage*/,
1839                        null /*finishedReceiver*/, updateUsers);
1840
1841                // Send replaced for users that don't see the package for the first time
1842                if (update) {
1843                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1844                            packageName, extras, 0 /*flags*/,
1845                            null /*targetPackage*/, null /*finishedReceiver*/,
1846                            updateUsers);
1847                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1848                            null /*package*/, null /*extras*/, 0 /*flags*/,
1849                            packageName /*targetPackage*/,
1850                            null /*finishedReceiver*/, updateUsers);
1851                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1852                    // First-install and we did a restore, so we're responsible for the
1853                    // first-launch broadcast.
1854                    if (DEBUG_BACKUP) {
1855                        Slog.i(TAG, "Post-restore of " + packageName
1856                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1857                    }
1858                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1859                }
1860
1861                // Send broadcast package appeared if forward locked/external for all users
1862                // treat asec-hosted packages like removable media on upgrade
1863                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1864                    if (DEBUG_INSTALL) {
1865                        Slog.i(TAG, "upgrading pkg " + res.pkg
1866                                + " is ASEC-hosted -> AVAILABLE");
1867                    }
1868                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1869                    ArrayList<String> pkgList = new ArrayList<>(1);
1870                    pkgList.add(packageName);
1871                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1872                }
1873            }
1874
1875            // Work that needs to happen on first install within each user
1876            if (firstUsers != null && firstUsers.length > 0) {
1877                synchronized (mPackages) {
1878                    for (int userId : firstUsers) {
1879                        // If this app is a browser and it's newly-installed for some
1880                        // users, clear any default-browser state in those users. The
1881                        // app's nature doesn't depend on the user, so we can just check
1882                        // its browser nature in any user and generalize.
1883                        if (packageIsBrowser(packageName, userId)) {
1884                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1885                        }
1886
1887                        // We may also need to apply pending (restored) runtime
1888                        // permission grants within these users.
1889                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1890                    }
1891                }
1892            }
1893
1894            // Log current value of "unknown sources" setting
1895            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1896                    getUnknownSourcesSettings());
1897
1898            // Force a gc to clear up things
1899            Runtime.getRuntime().gc();
1900
1901            // Remove the replaced package's older resources safely now
1902            // We delete after a gc for applications  on sdcard.
1903            if (res.removedInfo != null && res.removedInfo.args != null) {
1904                synchronized (mInstallLock) {
1905                    res.removedInfo.args.doPostDeleteLI(true);
1906                }
1907            }
1908
1909            // Notify DexManager that the package was installed for new users.
1910            // The updated users should already be indexed and the package code paths
1911            // should not change.
1912            // Don't notify the manager for ephemeral apps as they are not expected to
1913            // survive long enough to benefit of background optimizations.
1914            for (int userId : firstUsers) {
1915                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1916                mDexManager.notifyPackageInstalled(info, userId);
1917            }
1918        }
1919
1920        // If someone is watching installs - notify them
1921        if (installObserver != null) {
1922            try {
1923                Bundle extras = extrasForInstallResult(res);
1924                installObserver.onPackageInstalled(res.name, res.returnCode,
1925                        res.returnMsg, extras);
1926            } catch (RemoteException e) {
1927                Slog.i(TAG, "Observer no longer exists.");
1928            }
1929        }
1930    }
1931
1932    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1933            PackageParser.Package pkg) {
1934        if (pkg.parentPackage == null) {
1935            return;
1936        }
1937        if (pkg.requestedPermissions == null) {
1938            return;
1939        }
1940        final PackageSetting disabledSysParentPs = mSettings
1941                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1942        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1943                || !disabledSysParentPs.isPrivileged()
1944                || (disabledSysParentPs.childPackageNames != null
1945                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1946            return;
1947        }
1948        final int[] allUserIds = sUserManager.getUserIds();
1949        final int permCount = pkg.requestedPermissions.size();
1950        for (int i = 0; i < permCount; i++) {
1951            String permission = pkg.requestedPermissions.get(i);
1952            BasePermission bp = mSettings.mPermissions.get(permission);
1953            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1954                continue;
1955            }
1956            for (int userId : allUserIds) {
1957                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1958                        permission, userId)) {
1959                    grantRuntimePermission(pkg.packageName, permission, userId);
1960                }
1961            }
1962        }
1963    }
1964
1965    private StorageEventListener mStorageListener = new StorageEventListener() {
1966        @Override
1967        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1968            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1969                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1970                    final String volumeUuid = vol.getFsUuid();
1971
1972                    // Clean up any users or apps that were removed or recreated
1973                    // while this volume was missing
1974                    sUserManager.reconcileUsers(volumeUuid);
1975                    reconcileApps(volumeUuid);
1976
1977                    // Clean up any install sessions that expired or were
1978                    // cancelled while this volume was missing
1979                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1980
1981                    loadPrivatePackages(vol);
1982
1983                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1984                    unloadPrivatePackages(vol);
1985                }
1986            }
1987
1988            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1989                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1990                    updateExternalMediaStatus(true, false);
1991                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1992                    updateExternalMediaStatus(false, false);
1993                }
1994            }
1995        }
1996
1997        @Override
1998        public void onVolumeForgotten(String fsUuid) {
1999            if (TextUtils.isEmpty(fsUuid)) {
2000                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2001                return;
2002            }
2003
2004            // Remove any apps installed on the forgotten volume
2005            synchronized (mPackages) {
2006                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2007                for (PackageSetting ps : packages) {
2008                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2009                    deletePackageVersioned(new VersionedPackage(ps.name,
2010                            PackageManager.VERSION_CODE_HIGHEST),
2011                            new LegacyPackageDeleteObserver(null).getBinder(),
2012                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2013                    // Try very hard to release any references to this package
2014                    // so we don't risk the system server being killed due to
2015                    // open FDs
2016                    AttributeCache.instance().removePackage(ps.name);
2017                }
2018
2019                mSettings.onVolumeForgotten(fsUuid);
2020                mSettings.writeLPr();
2021            }
2022        }
2023    };
2024
2025    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2026            String[] grantedPermissions) {
2027        for (int userId : userIds) {
2028            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2029        }
2030    }
2031
2032    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2033            String[] grantedPermissions) {
2034        SettingBase sb = (SettingBase) pkg.mExtras;
2035        if (sb == null) {
2036            return;
2037        }
2038
2039        PermissionsState permissionsState = sb.getPermissionsState();
2040
2041        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2042                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2043
2044        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2045                >= Build.VERSION_CODES.M;
2046
2047        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2048
2049        for (String permission : pkg.requestedPermissions) {
2050            final BasePermission bp;
2051            synchronized (mPackages) {
2052                bp = mSettings.mPermissions.get(permission);
2053            }
2054            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2055                    && (!instantApp || bp.isInstant())
2056                    && (grantedPermissions == null
2057                           || ArrayUtils.contains(grantedPermissions, permission))) {
2058                final int flags = permissionsState.getPermissionFlags(permission, userId);
2059                if (supportsRuntimePermissions) {
2060                    // Installer cannot change immutable permissions.
2061                    if ((flags & immutableFlags) == 0) {
2062                        grantRuntimePermission(pkg.packageName, permission, userId);
2063                    }
2064                } else if (mPermissionReviewRequired) {
2065                    // In permission review mode we clear the review flag when we
2066                    // are asked to install the app with all permissions granted.
2067                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2068                        updatePermissionFlags(permission, pkg.packageName,
2069                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2070                    }
2071                }
2072            }
2073        }
2074    }
2075
2076    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2077        Bundle extras = null;
2078        switch (res.returnCode) {
2079            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2080                extras = new Bundle();
2081                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2082                        res.origPermission);
2083                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2084                        res.origPackage);
2085                break;
2086            }
2087            case PackageManager.INSTALL_SUCCEEDED: {
2088                extras = new Bundle();
2089                extras.putBoolean(Intent.EXTRA_REPLACING,
2090                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2091                break;
2092            }
2093        }
2094        return extras;
2095    }
2096
2097    void scheduleWriteSettingsLocked() {
2098        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2099            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2100        }
2101    }
2102
2103    void scheduleWritePackageListLocked(int userId) {
2104        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2105            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2106            msg.arg1 = userId;
2107            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2108        }
2109    }
2110
2111    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2112        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2113        scheduleWritePackageRestrictionsLocked(userId);
2114    }
2115
2116    void scheduleWritePackageRestrictionsLocked(int userId) {
2117        final int[] userIds = (userId == UserHandle.USER_ALL)
2118                ? sUserManager.getUserIds() : new int[]{userId};
2119        for (int nextUserId : userIds) {
2120            if (!sUserManager.exists(nextUserId)) return;
2121            mDirtyUsers.add(nextUserId);
2122            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2123                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2124            }
2125        }
2126    }
2127
2128    public static PackageManagerService main(Context context, Installer installer,
2129            boolean factoryTest, boolean onlyCore) {
2130        // Self-check for initial settings.
2131        PackageManagerServiceCompilerMapping.checkProperties();
2132
2133        PackageManagerService m = new PackageManagerService(context, installer,
2134                factoryTest, onlyCore);
2135        m.enableSystemUserPackages();
2136        ServiceManager.addService("package", m);
2137        return m;
2138    }
2139
2140    private void enableSystemUserPackages() {
2141        if (!UserManager.isSplitSystemUser()) {
2142            return;
2143        }
2144        // For system user, enable apps based on the following conditions:
2145        // - app is whitelisted or belong to one of these groups:
2146        //   -- system app which has no launcher icons
2147        //   -- system app which has INTERACT_ACROSS_USERS permission
2148        //   -- system IME app
2149        // - app is not in the blacklist
2150        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2151        Set<String> enableApps = new ArraySet<>();
2152        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2153                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2154                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2155        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2156        enableApps.addAll(wlApps);
2157        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2158                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2159        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2160        enableApps.removeAll(blApps);
2161        Log.i(TAG, "Applications installed for system user: " + enableApps);
2162        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2163                UserHandle.SYSTEM);
2164        final int allAppsSize = allAps.size();
2165        synchronized (mPackages) {
2166            for (int i = 0; i < allAppsSize; i++) {
2167                String pName = allAps.get(i);
2168                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2169                // Should not happen, but we shouldn't be failing if it does
2170                if (pkgSetting == null) {
2171                    continue;
2172                }
2173                boolean install = enableApps.contains(pName);
2174                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2175                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2176                            + " for system user");
2177                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2178                }
2179            }
2180            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2181        }
2182    }
2183
2184    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2185        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2186                Context.DISPLAY_SERVICE);
2187        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2188    }
2189
2190    /**
2191     * Requests that files preopted on a secondary system partition be copied to the data partition
2192     * if possible.  Note that the actual copying of the files is accomplished by init for security
2193     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2194     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2195     */
2196    private static void requestCopyPreoptedFiles() {
2197        final int WAIT_TIME_MS = 100;
2198        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2199        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2200            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2201            // We will wait for up to 100 seconds.
2202            final long timeStart = SystemClock.uptimeMillis();
2203            final long timeEnd = timeStart + 100 * 1000;
2204            long timeNow = timeStart;
2205            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2206                try {
2207                    Thread.sleep(WAIT_TIME_MS);
2208                } catch (InterruptedException e) {
2209                    // Do nothing
2210                }
2211                timeNow = SystemClock.uptimeMillis();
2212                if (timeNow > timeEnd) {
2213                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2214                    Slog.wtf(TAG, "cppreopt did not finish!");
2215                    break;
2216                }
2217            }
2218
2219            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2220        }
2221    }
2222
2223    public PackageManagerService(Context context, Installer installer,
2224            boolean factoryTest, boolean onlyCore) {
2225        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2226        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2227        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2228                SystemClock.uptimeMillis());
2229
2230        if (mSdkVersion <= 0) {
2231            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2232        }
2233
2234        mContext = context;
2235
2236        mPermissionReviewRequired = context.getResources().getBoolean(
2237                R.bool.config_permissionReviewRequired);
2238
2239        mFactoryTest = factoryTest;
2240        mOnlyCore = onlyCore;
2241        mMetrics = new DisplayMetrics();
2242        mSettings = new Settings(mPackages);
2243        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2250                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2251        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2252                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2253        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2254                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2255
2256        String separateProcesses = SystemProperties.get("debug.separate_processes");
2257        if (separateProcesses != null && separateProcesses.length() > 0) {
2258            if ("*".equals(separateProcesses)) {
2259                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2260                mSeparateProcesses = null;
2261                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2262            } else {
2263                mDefParseFlags = 0;
2264                mSeparateProcesses = separateProcesses.split(",");
2265                Slog.w(TAG, "Running with debug.separate_processes: "
2266                        + separateProcesses);
2267            }
2268        } else {
2269            mDefParseFlags = 0;
2270            mSeparateProcesses = null;
2271        }
2272
2273        mInstaller = installer;
2274        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2275                "*dexopt*");
2276        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2277        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2278
2279        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2280                FgThread.get().getLooper());
2281
2282        getDefaultDisplayMetrics(context, mMetrics);
2283
2284        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2285        SystemConfig systemConfig = SystemConfig.getInstance();
2286        mGlobalGids = systemConfig.getGlobalGids();
2287        mSystemPermissions = systemConfig.getSystemPermissions();
2288        mAvailableFeatures = systemConfig.getAvailableFeatures();
2289        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2290
2291        mProtectedPackages = new ProtectedPackages(mContext);
2292
2293        synchronized (mInstallLock) {
2294        // writer
2295        synchronized (mPackages) {
2296            mHandlerThread = new ServiceThread(TAG,
2297                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2298            mHandlerThread.start();
2299            mHandler = new PackageHandler(mHandlerThread.getLooper());
2300            mProcessLoggingHandler = new ProcessLoggingHandler();
2301            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2302
2303            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2304            mInstantAppRegistry = new InstantAppRegistry(this);
2305
2306            File dataDir = Environment.getDataDirectory();
2307            mAppInstallDir = new File(dataDir, "app");
2308            mAppLib32InstallDir = new File(dataDir, "app-lib");
2309            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2310            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2311            sUserManager = new UserManagerService(context, this,
2312                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2313
2314            // Propagate permission configuration in to package manager.
2315            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2316                    = systemConfig.getPermissions();
2317            for (int i=0; i<permConfig.size(); i++) {
2318                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2319                BasePermission bp = mSettings.mPermissions.get(perm.name);
2320                if (bp == null) {
2321                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2322                    mSettings.mPermissions.put(perm.name, bp);
2323                }
2324                if (perm.gids != null) {
2325                    bp.setGids(perm.gids, perm.perUser);
2326                }
2327            }
2328
2329            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2330            final int builtInLibCount = libConfig.size();
2331            for (int i = 0; i < builtInLibCount; i++) {
2332                String name = libConfig.keyAt(i);
2333                String path = libConfig.valueAt(i);
2334                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2335                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2336            }
2337
2338            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2339
2340            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2341            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2343
2344            // Clean up orphaned packages for which the code path doesn't exist
2345            // and they are an update to a system app - caused by bug/32321269
2346            final int packageSettingCount = mSettings.mPackages.size();
2347            for (int i = packageSettingCount - 1; i >= 0; i--) {
2348                PackageSetting ps = mSettings.mPackages.valueAt(i);
2349                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2350                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2351                    mSettings.mPackages.removeAt(i);
2352                    mSettings.enableSystemPackageLPw(ps.name);
2353                }
2354            }
2355
2356            if (mFirstBoot) {
2357                requestCopyPreoptedFiles();
2358            }
2359
2360            String customResolverActivity = Resources.getSystem().getString(
2361                    R.string.config_customResolverActivity);
2362            if (TextUtils.isEmpty(customResolverActivity)) {
2363                customResolverActivity = null;
2364            } else {
2365                mCustomResolverComponentName = ComponentName.unflattenFromString(
2366                        customResolverActivity);
2367            }
2368
2369            long startTime = SystemClock.uptimeMillis();
2370
2371            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2372                    startTime);
2373
2374            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2375            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2376
2377            if (bootClassPath == null) {
2378                Slog.w(TAG, "No BOOTCLASSPATH found!");
2379            }
2380
2381            if (systemServerClassPath == null) {
2382                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2383            }
2384
2385            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2386
2387            final VersionInfo ver = mSettings.getInternalVersion();
2388            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2389
2390            // when upgrading from pre-M, promote system app permissions from install to runtime
2391            mPromoteSystemApps =
2392                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2393
2394            // When upgrading from pre-N, we need to handle package extraction like first boot,
2395            // as there is no profiling data available.
2396            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2397
2398            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2399
2400            // save off the names of pre-existing system packages prior to scanning; we don't
2401            // want to automatically grant runtime permissions for new system apps
2402            if (mPromoteSystemApps) {
2403                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2404                while (pkgSettingIter.hasNext()) {
2405                    PackageSetting ps = pkgSettingIter.next();
2406                    if (isSystemApp(ps)) {
2407                        mExistingSystemPackages.add(ps.name);
2408                    }
2409                }
2410            }
2411
2412            mCacheDir = preparePackageParserCache(mIsUpgrade);
2413
2414            // Set flag to monitor and not change apk file paths when
2415            // scanning install directories.
2416            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2417
2418            if (mIsUpgrade || mFirstBoot) {
2419                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2420            }
2421
2422            // Collect vendor overlay packages. (Do this before scanning any apps.)
2423            // For security and version matching reason, only consider
2424            // overlay packages if they reside in the right directory.
2425            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2426                    | PackageParser.PARSE_IS_SYSTEM
2427                    | PackageParser.PARSE_IS_SYSTEM_DIR
2428                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2429
2430            // Find base frameworks (resource packages without code).
2431            scanDirTracedLI(frameworkDir, mDefParseFlags
2432                    | PackageParser.PARSE_IS_SYSTEM
2433                    | PackageParser.PARSE_IS_SYSTEM_DIR
2434                    | PackageParser.PARSE_IS_PRIVILEGED,
2435                    scanFlags | SCAN_NO_DEX, 0);
2436
2437            // Collected privileged system packages.
2438            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2439            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2440                    | PackageParser.PARSE_IS_SYSTEM
2441                    | PackageParser.PARSE_IS_SYSTEM_DIR
2442                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2443
2444            // Collect ordinary system packages.
2445            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2446            scanDirTracedLI(systemAppDir, mDefParseFlags
2447                    | PackageParser.PARSE_IS_SYSTEM
2448                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2449
2450            // Collect all vendor packages.
2451            File vendorAppDir = new File("/vendor/app");
2452            try {
2453                vendorAppDir = vendorAppDir.getCanonicalFile();
2454            } catch (IOException e) {
2455                // failed to look up canonical path, continue with original one
2456            }
2457            scanDirTracedLI(vendorAppDir, mDefParseFlags
2458                    | PackageParser.PARSE_IS_SYSTEM
2459                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2460
2461            // Collect all OEM packages.
2462            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2463            scanDirTracedLI(oemAppDir, mDefParseFlags
2464                    | PackageParser.PARSE_IS_SYSTEM
2465                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2466
2467            // Prune any system packages that no longer exist.
2468            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2469            if (!mOnlyCore) {
2470                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2471                while (psit.hasNext()) {
2472                    PackageSetting ps = psit.next();
2473
2474                    /*
2475                     * If this is not a system app, it can't be a
2476                     * disable system app.
2477                     */
2478                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2479                        continue;
2480                    }
2481
2482                    /*
2483                     * If the package is scanned, it's not erased.
2484                     */
2485                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2486                    if (scannedPkg != null) {
2487                        /*
2488                         * If the system app is both scanned and in the
2489                         * disabled packages list, then it must have been
2490                         * added via OTA. Remove it from the currently
2491                         * scanned package so the previously user-installed
2492                         * application can be scanned.
2493                         */
2494                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2495                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2496                                    + ps.name + "; removing system app.  Last known codePath="
2497                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2498                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2499                                    + scannedPkg.mVersionCode);
2500                            removePackageLI(scannedPkg, true);
2501                            mExpectingBetter.put(ps.name, ps.codePath);
2502                        }
2503
2504                        continue;
2505                    }
2506
2507                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2508                        psit.remove();
2509                        logCriticalInfo(Log.WARN, "System package " + ps.name
2510                                + " no longer exists; it's data will be wiped");
2511                        // Actual deletion of code and data will be handled by later
2512                        // reconciliation step
2513                    } else {
2514                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2515                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2516                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2517                        }
2518                    }
2519                }
2520            }
2521
2522            //look for any incomplete package installations
2523            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2524            for (int i = 0; i < deletePkgsList.size(); i++) {
2525                // Actual deletion of code and data will be handled by later
2526                // reconciliation step
2527                final String packageName = deletePkgsList.get(i).name;
2528                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2529                synchronized (mPackages) {
2530                    mSettings.removePackageLPw(packageName);
2531                }
2532            }
2533
2534            //delete tmp files
2535            deleteTempPackageFiles();
2536
2537            // Remove any shared userIDs that have no associated packages
2538            mSettings.pruneSharedUsersLPw();
2539
2540            if (!mOnlyCore) {
2541                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2542                        SystemClock.uptimeMillis());
2543                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2544
2545                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2546                        | PackageParser.PARSE_FORWARD_LOCK,
2547                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2548
2549                /**
2550                 * Remove disable package settings for any updated system
2551                 * apps that were removed via an OTA. If they're not a
2552                 * previously-updated app, remove them completely.
2553                 * Otherwise, just revoke their system-level permissions.
2554                 */
2555                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2556                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2557                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2558
2559                    String msg;
2560                    if (deletedPkg == null) {
2561                        msg = "Updated system package " + deletedAppName
2562                                + " no longer exists; it's data will be wiped";
2563                        // Actual deletion of code and data will be handled by later
2564                        // reconciliation step
2565                    } else {
2566                        msg = "Updated system app + " + deletedAppName
2567                                + " no longer present; removing system privileges for "
2568                                + deletedAppName;
2569
2570                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2571
2572                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2573                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2574                    }
2575                    logCriticalInfo(Log.WARN, msg);
2576                }
2577
2578                /**
2579                 * Make sure all system apps that we expected to appear on
2580                 * the userdata partition actually showed up. If they never
2581                 * appeared, crawl back and revive the system version.
2582                 */
2583                for (int i = 0; i < mExpectingBetter.size(); i++) {
2584                    final String packageName = mExpectingBetter.keyAt(i);
2585                    if (!mPackages.containsKey(packageName)) {
2586                        final File scanFile = mExpectingBetter.valueAt(i);
2587
2588                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2589                                + " but never showed up; reverting to system");
2590
2591                        int reparseFlags = mDefParseFlags;
2592                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2593                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2594                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2595                                    | PackageParser.PARSE_IS_PRIVILEGED;
2596                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2597                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2598                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2599                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2600                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2601                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2602                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2603                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2604                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2605                        } else {
2606                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2607                            continue;
2608                        }
2609
2610                        mSettings.enableSystemPackageLPw(packageName);
2611
2612                        try {
2613                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2614                        } catch (PackageManagerException e) {
2615                            Slog.e(TAG, "Failed to parse original system package: "
2616                                    + e.getMessage());
2617                        }
2618                    }
2619                }
2620            }
2621            mExpectingBetter.clear();
2622
2623            // Resolve the storage manager.
2624            mStorageManagerPackage = getStorageManagerPackageName();
2625
2626            // Resolve protected action filters. Only the setup wizard is allowed to
2627            // have a high priority filter for these actions.
2628            mSetupWizardPackage = getSetupWizardPackageName();
2629            if (mProtectedFilters.size() > 0) {
2630                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2631                    Slog.i(TAG, "No setup wizard;"
2632                        + " All protected intents capped to priority 0");
2633                }
2634                for (ActivityIntentInfo filter : mProtectedFilters) {
2635                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2636                        if (DEBUG_FILTERS) {
2637                            Slog.i(TAG, "Found setup wizard;"
2638                                + " allow priority " + filter.getPriority() + ";"
2639                                + " package: " + filter.activity.info.packageName
2640                                + " activity: " + filter.activity.className
2641                                + " priority: " + filter.getPriority());
2642                        }
2643                        // skip setup wizard; allow it to keep the high priority filter
2644                        continue;
2645                    }
2646                    Slog.w(TAG, "Protected action; cap priority to 0;"
2647                            + " package: " + filter.activity.info.packageName
2648                            + " activity: " + filter.activity.className
2649                            + " origPrio: " + filter.getPriority());
2650                    filter.setPriority(0);
2651                }
2652            }
2653            mDeferProtectedFilters = false;
2654            mProtectedFilters.clear();
2655
2656            // Now that we know all of the shared libraries, update all clients to have
2657            // the correct library paths.
2658            updateAllSharedLibrariesLPw(null);
2659
2660            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2661                // NOTE: We ignore potential failures here during a system scan (like
2662                // the rest of the commands above) because there's precious little we
2663                // can do about it. A settings error is reported, though.
2664                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2665            }
2666
2667            // Now that we know all the packages we are keeping,
2668            // read and update their last usage times.
2669            mPackageUsage.read(mPackages);
2670            mCompilerStats.read();
2671
2672            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2673                    SystemClock.uptimeMillis());
2674            Slog.i(TAG, "Time to scan packages: "
2675                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2676                    + " seconds");
2677
2678            // If the platform SDK has changed since the last time we booted,
2679            // we need to re-grant app permission to catch any new ones that
2680            // appear.  This is really a hack, and means that apps can in some
2681            // cases get permissions that the user didn't initially explicitly
2682            // allow...  it would be nice to have some better way to handle
2683            // this situation.
2684            int updateFlags = UPDATE_PERMISSIONS_ALL;
2685            if (ver.sdkVersion != mSdkVersion) {
2686                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2687                        + mSdkVersion + "; regranting permissions for internal storage");
2688                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2689            }
2690            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2691            ver.sdkVersion = mSdkVersion;
2692
2693            // If this is the first boot or an update from pre-M, and it is a normal
2694            // boot, then we need to initialize the default preferred apps across
2695            // all defined users.
2696            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2697                for (UserInfo user : sUserManager.getUsers(true)) {
2698                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2699                    applyFactoryDefaultBrowserLPw(user.id);
2700                    primeDomainVerificationsLPw(user.id);
2701                }
2702            }
2703
2704            // Prepare storage for system user really early during boot,
2705            // since core system apps like SettingsProvider and SystemUI
2706            // can't wait for user to start
2707            final int storageFlags;
2708            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2709                storageFlags = StorageManager.FLAG_STORAGE_DE;
2710            } else {
2711                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2712            }
2713            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2714                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2715                    true /* onlyCoreApps */);
2716            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2717                if (deferPackages == null || deferPackages.isEmpty()) {
2718                    return;
2719                }
2720                int count = 0;
2721                for (String pkgName : deferPackages) {
2722                    PackageParser.Package pkg = null;
2723                    synchronized (mPackages) {
2724                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2725                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2726                            pkg = ps.pkg;
2727                        }
2728                    }
2729                    if (pkg != null) {
2730                        synchronized (mInstallLock) {
2731                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2732                                    true /* maybeMigrateAppData */);
2733                        }
2734                        count++;
2735                    }
2736                }
2737                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2738            }, "prepareAppData");
2739
2740            // If this is first boot after an OTA, and a normal boot, then
2741            // we need to clear code cache directories.
2742            // Note that we do *not* clear the application profiles. These remain valid
2743            // across OTAs and are used to drive profile verification (post OTA) and
2744            // profile compilation (without waiting to collect a fresh set of profiles).
2745            if (mIsUpgrade && !onlyCore) {
2746                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2747                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2748                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2749                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2750                        // No apps are running this early, so no need to freeze
2751                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2752                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2753                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2754                    }
2755                }
2756                ver.fingerprint = Build.FINGERPRINT;
2757            }
2758
2759            checkDefaultBrowser();
2760
2761            // clear only after permissions and other defaults have been updated
2762            mExistingSystemPackages.clear();
2763            mPromoteSystemApps = false;
2764
2765            // All the changes are done during package scanning.
2766            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2767
2768            // can downgrade to reader
2769            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2770            mSettings.writeLPr();
2771            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2772
2773            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2774                    SystemClock.uptimeMillis());
2775
2776            if (!mOnlyCore) {
2777                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2778                mRequiredInstallerPackage = getRequiredInstallerLPr();
2779                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2780                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2781                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2782                        mIntentFilterVerifierComponent);
2783                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2784                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2785                        SharedLibraryInfo.VERSION_UNDEFINED);
2786                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2787                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2788                        SharedLibraryInfo.VERSION_UNDEFINED);
2789            } else {
2790                mRequiredVerifierPackage = null;
2791                mRequiredInstallerPackage = null;
2792                mRequiredUninstallerPackage = null;
2793                mIntentFilterVerifierComponent = null;
2794                mIntentFilterVerifier = null;
2795                mServicesSystemSharedLibraryPackageName = null;
2796                mSharedSystemSharedLibraryPackageName = null;
2797            }
2798
2799            mInstallerService = new PackageInstallerService(context, this);
2800            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2801            if (ephemeralResolverComponent != null) {
2802                if (DEBUG_EPHEMERAL) {
2803                    Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent);
2804                }
2805                mInstantAppResolverConnection =
2806                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2807            } else {
2808                mInstantAppResolverConnection = null;
2809            }
2810            updateInstantAppInstallerLocked();
2811            mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr();
2812
2813            // Read and update the usage of dex files.
2814            // Do this at the end of PM init so that all the packages have their
2815            // data directory reconciled.
2816            // At this point we know the code paths of the packages, so we can validate
2817            // the disk file and build the internal cache.
2818            // The usage file is expected to be small so loading and verifying it
2819            // should take a fairly small time compare to the other activities (e.g. package
2820            // scanning).
2821            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2822            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2823            for (int userId : currentUserIds) {
2824                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2825            }
2826            mDexManager.load(userPackages);
2827        } // synchronized (mPackages)
2828        } // synchronized (mInstallLock)
2829
2830        // Now after opening every single application zip, make sure they
2831        // are all flushed.  Not really needed, but keeps things nice and
2832        // tidy.
2833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2834        Runtime.getRuntime().gc();
2835        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2836
2837        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2838        FallbackCategoryProvider.loadFallbacks();
2839        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2840
2841        // The initial scanning above does many calls into installd while
2842        // holding the mPackages lock, but we're mostly interested in yelling
2843        // once we have a booted system.
2844        mInstaller.setWarnIfHeld(mPackages);
2845
2846        // Expose private service for system components to use.
2847        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2848        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2849    }
2850
2851    private void updateInstantAppInstallerLocked() {
2852        final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent;
2853        final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr();
2854        ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null
2855                ? null : newInstantAppInstaller.getComponentName();
2856
2857        if (newInstantAppInstallerComponent != null
2858                && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) {
2859            if (DEBUG_EPHEMERAL) {
2860                Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent);
2861            }
2862            setUpInstantAppInstallerActivityLP(newInstantAppInstaller);
2863        } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) {
2864            Slog.d(TAG, "Unset ephemeral installer; none available");
2865        }
2866        mInstantAppInstallerComponent = newInstantAppInstallerComponent;
2867    }
2868
2869    private static File preparePackageParserCache(boolean isUpgrade) {
2870        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2871            return null;
2872        }
2873
2874        // Disable package parsing on eng builds to allow for faster incremental development.
2875        if ("eng".equals(Build.TYPE)) {
2876            return null;
2877        }
2878
2879        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2880            Slog.i(TAG, "Disabling package parser cache due to system property.");
2881            return null;
2882        }
2883
2884        // The base directory for the package parser cache lives under /data/system/.
2885        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2886                "package_cache");
2887        if (cacheBaseDir == null) {
2888            return null;
2889        }
2890
2891        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2892        // This also serves to "GC" unused entries when the package cache version changes (which
2893        // can only happen during upgrades).
2894        if (isUpgrade) {
2895            FileUtils.deleteContents(cacheBaseDir);
2896        }
2897
2898
2899        // Return the versioned package cache directory. This is something like
2900        // "/data/system/package_cache/1"
2901        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2902
2903        // The following is a workaround to aid development on non-numbered userdebug
2904        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2905        // the system partition is newer.
2906        //
2907        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2908        // that starts with "eng." to signify that this is an engineering build and not
2909        // destined for release.
2910        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2911            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2912
2913            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2914            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2915            // in general and should not be used for production changes. In this specific case,
2916            // we know that they will work.
2917            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2918            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2919                FileUtils.deleteContents(cacheBaseDir);
2920                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2921            }
2922        }
2923
2924        return cacheDir;
2925    }
2926
2927    @Override
2928    public boolean isFirstBoot() {
2929        return mFirstBoot;
2930    }
2931
2932    @Override
2933    public boolean isOnlyCoreApps() {
2934        return mOnlyCore;
2935    }
2936
2937    @Override
2938    public boolean isUpgrade() {
2939        return mIsUpgrade;
2940    }
2941
2942    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2943        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2944
2945        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2946                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2947                UserHandle.USER_SYSTEM);
2948        if (matches.size() == 1) {
2949            return matches.get(0).getComponentInfo().packageName;
2950        } else if (matches.size() == 0) {
2951            Log.e(TAG, "There should probably be a verifier, but, none were found");
2952            return null;
2953        }
2954        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2955    }
2956
2957    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2958        synchronized (mPackages) {
2959            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2960            if (libraryEntry == null) {
2961                throw new IllegalStateException("Missing required shared library:" + name);
2962            }
2963            return libraryEntry.apk;
2964        }
2965    }
2966
2967    private @NonNull String getRequiredInstallerLPr() {
2968        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2969        intent.addCategory(Intent.CATEGORY_DEFAULT);
2970        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2971
2972        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2973                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2974                UserHandle.USER_SYSTEM);
2975        if (matches.size() == 1) {
2976            ResolveInfo resolveInfo = matches.get(0);
2977            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2978                throw new RuntimeException("The installer must be a privileged app");
2979            }
2980            return matches.get(0).getComponentInfo().packageName;
2981        } else {
2982            throw new RuntimeException("There must be exactly one installer; found " + matches);
2983        }
2984    }
2985
2986    private @NonNull String getRequiredUninstallerLPr() {
2987        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2988        intent.addCategory(Intent.CATEGORY_DEFAULT);
2989        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2990
2991        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2992                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2993                UserHandle.USER_SYSTEM);
2994        if (resolveInfo == null ||
2995                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2996            throw new RuntimeException("There must be exactly one uninstaller; found "
2997                    + resolveInfo);
2998        }
2999        return resolveInfo.getComponentInfo().packageName;
3000    }
3001
3002    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3003        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3004
3005        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3006                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3007                UserHandle.USER_SYSTEM);
3008        ResolveInfo best = null;
3009        final int N = matches.size();
3010        for (int i = 0; i < N; i++) {
3011            final ResolveInfo cur = matches.get(i);
3012            final String packageName = cur.getComponentInfo().packageName;
3013            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3014                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3015                continue;
3016            }
3017
3018            if (best == null || cur.priority > best.priority) {
3019                best = cur;
3020            }
3021        }
3022
3023        if (best != null) {
3024            return best.getComponentInfo().getComponentName();
3025        } else {
3026            throw new RuntimeException("There must be at least one intent filter verifier");
3027        }
3028    }
3029
3030    private @Nullable ComponentName getEphemeralResolverLPr() {
3031        final String[] packageArray =
3032                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3033        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3034            if (DEBUG_EPHEMERAL) {
3035                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3036            }
3037            return null;
3038        }
3039
3040        final int resolveFlags =
3041                MATCH_DIRECT_BOOT_AWARE
3042                | MATCH_DIRECT_BOOT_UNAWARE
3043                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3044        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3045        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3046                resolveFlags, UserHandle.USER_SYSTEM);
3047
3048        final int N = resolvers.size();
3049        if (N == 0) {
3050            if (DEBUG_EPHEMERAL) {
3051                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3052            }
3053            return null;
3054        }
3055
3056        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3057        for (int i = 0; i < N; i++) {
3058            final ResolveInfo info = resolvers.get(i);
3059
3060            if (info.serviceInfo == null) {
3061                continue;
3062            }
3063
3064            final String packageName = info.serviceInfo.packageName;
3065            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3066                if (DEBUG_EPHEMERAL) {
3067                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3068                            + " pkg: " + packageName + ", info:" + info);
3069                }
3070                continue;
3071            }
3072
3073            if (DEBUG_EPHEMERAL) {
3074                Slog.v(TAG, "Ephemeral resolver found;"
3075                        + " pkg: " + packageName + ", info:" + info);
3076            }
3077            return new ComponentName(packageName, info.serviceInfo.name);
3078        }
3079        if (DEBUG_EPHEMERAL) {
3080            Slog.v(TAG, "Ephemeral resolver NOT found");
3081        }
3082        return null;
3083    }
3084
3085    private @Nullable ActivityInfo getEphemeralInstallerLPr() {
3086        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3087        intent.addCategory(Intent.CATEGORY_DEFAULT);
3088        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3089
3090        final int resolveFlags =
3091                MATCH_DIRECT_BOOT_AWARE
3092                | MATCH_DIRECT_BOOT_UNAWARE
3093                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3094        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3095                resolveFlags, UserHandle.USER_SYSTEM);
3096        Iterator<ResolveInfo> iter = matches.iterator();
3097        while (iter.hasNext()) {
3098            final ResolveInfo rInfo = iter.next();
3099            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3100            if (ps != null) {
3101                final PermissionsState permissionsState = ps.getPermissionsState();
3102                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3103                    continue;
3104                }
3105            }
3106            iter.remove();
3107        }
3108        if (matches.size() == 0) {
3109            return null;
3110        } else if (matches.size() == 1) {
3111            return (ActivityInfo) matches.get(0).getComponentInfo();
3112        } else {
3113            throw new RuntimeException(
3114                    "There must be at most one ephemeral installer; found " + matches);
3115        }
3116    }
3117
3118    private @Nullable ComponentName getEphemeralResolverSettingsLPr() {
3119        final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3120        intent.addCategory(Intent.CATEGORY_DEFAULT);
3121        final int resolveFlags =
3122                MATCH_DIRECT_BOOT_AWARE
3123                | MATCH_DIRECT_BOOT_UNAWARE
3124                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3125        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
3126                resolveFlags, UserHandle.USER_SYSTEM);
3127        Iterator<ResolveInfo> iter = matches.iterator();
3128        while (iter.hasNext()) {
3129            final ResolveInfo rInfo = iter.next();
3130            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3131            if (ps != null) {
3132                final PermissionsState permissionsState = ps.getPermissionsState();
3133                if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) {
3134                    continue;
3135                }
3136            }
3137            iter.remove();
3138        }
3139        if (matches.size() == 0) {
3140            return null;
3141        } else if (matches.size() == 1) {
3142            return matches.get(0).getComponentInfo().getComponentName();
3143        } else {
3144            throw new RuntimeException(
3145                    "There must be at most one ephemeral resolver settings; found " + matches);
3146        }
3147    }
3148
3149    private void primeDomainVerificationsLPw(int userId) {
3150        if (DEBUG_DOMAIN_VERIFICATION) {
3151            Slog.d(TAG, "Priming domain verifications in user " + userId);
3152        }
3153
3154        SystemConfig systemConfig = SystemConfig.getInstance();
3155        ArraySet<String> packages = systemConfig.getLinkedApps();
3156
3157        for (String packageName : packages) {
3158            PackageParser.Package pkg = mPackages.get(packageName);
3159            if (pkg != null) {
3160                if (!pkg.isSystemApp()) {
3161                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3162                    continue;
3163                }
3164
3165                ArraySet<String> domains = null;
3166                for (PackageParser.Activity a : pkg.activities) {
3167                    for (ActivityIntentInfo filter : a.intents) {
3168                        if (hasValidDomains(filter)) {
3169                            if (domains == null) {
3170                                domains = new ArraySet<String>();
3171                            }
3172                            domains.addAll(filter.getHostsList());
3173                        }
3174                    }
3175                }
3176
3177                if (domains != null && domains.size() > 0) {
3178                    if (DEBUG_DOMAIN_VERIFICATION) {
3179                        Slog.v(TAG, "      + " + packageName);
3180                    }
3181                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3182                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3183                    // and then 'always' in the per-user state actually used for intent resolution.
3184                    final IntentFilterVerificationInfo ivi;
3185                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3186                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3187                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3188                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3189                } else {
3190                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3191                            + "' does not handle web links");
3192                }
3193            } else {
3194                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3195            }
3196        }
3197
3198        scheduleWritePackageRestrictionsLocked(userId);
3199        scheduleWriteSettingsLocked();
3200    }
3201
3202    private void applyFactoryDefaultBrowserLPw(int userId) {
3203        // The default browser app's package name is stored in a string resource,
3204        // with a product-specific overlay used for vendor customization.
3205        String browserPkg = mContext.getResources().getString(
3206                com.android.internal.R.string.default_browser);
3207        if (!TextUtils.isEmpty(browserPkg)) {
3208            // non-empty string => required to be a known package
3209            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3210            if (ps == null) {
3211                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3212                browserPkg = null;
3213            } else {
3214                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3215            }
3216        }
3217
3218        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3219        // default.  If there's more than one, just leave everything alone.
3220        if (browserPkg == null) {
3221            calculateDefaultBrowserLPw(userId);
3222        }
3223    }
3224
3225    private void calculateDefaultBrowserLPw(int userId) {
3226        List<String> allBrowsers = resolveAllBrowserApps(userId);
3227        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3228        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3229    }
3230
3231    private List<String> resolveAllBrowserApps(int userId) {
3232        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3233        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3234                PackageManager.MATCH_ALL, userId);
3235
3236        final int count = list.size();
3237        List<String> result = new ArrayList<String>(count);
3238        for (int i=0; i<count; i++) {
3239            ResolveInfo info = list.get(i);
3240            if (info.activityInfo == null
3241                    || !info.handleAllWebDataURI
3242                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3243                    || result.contains(info.activityInfo.packageName)) {
3244                continue;
3245            }
3246            result.add(info.activityInfo.packageName);
3247        }
3248
3249        return result;
3250    }
3251
3252    private boolean packageIsBrowser(String packageName, int userId) {
3253        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3254                PackageManager.MATCH_ALL, userId);
3255        final int N = list.size();
3256        for (int i = 0; i < N; i++) {
3257            ResolveInfo info = list.get(i);
3258            if (packageName.equals(info.activityInfo.packageName)) {
3259                return true;
3260            }
3261        }
3262        return false;
3263    }
3264
3265    private void checkDefaultBrowser() {
3266        final int myUserId = UserHandle.myUserId();
3267        final String packageName = getDefaultBrowserPackageName(myUserId);
3268        if (packageName != null) {
3269            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3270            if (info == null) {
3271                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3272                synchronized (mPackages) {
3273                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3274                }
3275            }
3276        }
3277    }
3278
3279    @Override
3280    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3281            throws RemoteException {
3282        try {
3283            return super.onTransact(code, data, reply, flags);
3284        } catch (RuntimeException e) {
3285            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3286                Slog.wtf(TAG, "Package Manager Crash", e);
3287            }
3288            throw e;
3289        }
3290    }
3291
3292    static int[] appendInts(int[] cur, int[] add) {
3293        if (add == null) return cur;
3294        if (cur == null) return add;
3295        final int N = add.length;
3296        for (int i=0; i<N; i++) {
3297            cur = appendInt(cur, add[i]);
3298        }
3299        return cur;
3300    }
3301
3302    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3303        if (!sUserManager.exists(userId)) return null;
3304        if (ps == null) {
3305            return null;
3306        }
3307        final PackageParser.Package p = ps.pkg;
3308        if (p == null) {
3309            return null;
3310        }
3311        // Filter out ephemeral app metadata:
3312        //   * The system/shell/root can see metadata for any app
3313        //   * An installed app can see metadata for 1) other installed apps
3314        //     and 2) ephemeral apps that have explicitly interacted with it
3315        //   * Ephemeral apps can only see their own data and exposed installed apps
3316        //   * Holding a signature permission allows seeing instant apps
3317        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3318        if (callingAppId != Process.SYSTEM_UID
3319                && callingAppId != Process.SHELL_UID
3320                && callingAppId != Process.ROOT_UID
3321                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3322                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3323            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3324            if (instantAppPackageName != null) {
3325                // ephemeral apps can only get information on themselves or
3326                // installed apps that are exposed.
3327                if (!instantAppPackageName.equals(p.packageName)
3328                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3329                    return null;
3330                }
3331            } else {
3332                if (ps.getInstantApp(userId)) {
3333                    // only get access to the ephemeral app if we've been granted access
3334                    if (!mInstantAppRegistry.isInstantAccessGranted(
3335                            userId, callingAppId, ps.appId)) {
3336                        return null;
3337                    }
3338                }
3339            }
3340        }
3341
3342        final PermissionsState permissionsState = ps.getPermissionsState();
3343
3344        // Compute GIDs only if requested
3345        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3346                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3347        // Compute granted permissions only if package has requested permissions
3348        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3349                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3350        final PackageUserState state = ps.readUserState(userId);
3351
3352        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3353                && ps.isSystem()) {
3354            flags |= MATCH_ANY_USER;
3355        }
3356
3357        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3358                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3359
3360        if (packageInfo == null) {
3361            return null;
3362        }
3363
3364        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3365
3366        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3367                resolveExternalPackageNameLPr(p);
3368
3369        return packageInfo;
3370    }
3371
3372    @Override
3373    public void checkPackageStartable(String packageName, int userId) {
3374        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3375
3376        synchronized (mPackages) {
3377            final PackageSetting ps = mSettings.mPackages.get(packageName);
3378            if (ps == null) {
3379                throw new SecurityException("Package " + packageName + " was not found!");
3380            }
3381
3382            if (!ps.getInstalled(userId)) {
3383                throw new SecurityException(
3384                        "Package " + packageName + " was not installed for user " + userId + "!");
3385            }
3386
3387            if (mSafeMode && !ps.isSystem()) {
3388                throw new SecurityException("Package " + packageName + " not a system app!");
3389            }
3390
3391            if (mFrozenPackages.contains(packageName)) {
3392                throw new SecurityException("Package " + packageName + " is currently frozen!");
3393            }
3394
3395            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3396                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3397                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3398            }
3399        }
3400    }
3401
3402    @Override
3403    public boolean isPackageAvailable(String packageName, int userId) {
3404        if (!sUserManager.exists(userId)) return false;
3405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3406                false /* requireFullPermission */, false /* checkShell */, "is package available");
3407        synchronized (mPackages) {
3408            PackageParser.Package p = mPackages.get(packageName);
3409            if (p != null) {
3410                final PackageSetting ps = (PackageSetting) p.mExtras;
3411                if (ps != null) {
3412                    final PackageUserState state = ps.readUserState(userId);
3413                    if (state != null) {
3414                        return PackageParser.isAvailable(state);
3415                    }
3416                }
3417            }
3418        }
3419        return false;
3420    }
3421
3422    @Override
3423    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3424        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3425                flags, userId);
3426    }
3427
3428    @Override
3429    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3430            int flags, int userId) {
3431        return getPackageInfoInternal(versionedPackage.getPackageName(),
3432                // TODO: We will change version code to long, so in the new API it is long
3433                (int) versionedPackage.getVersionCode(), flags, userId);
3434    }
3435
3436    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3437            int flags, int userId) {
3438        if (!sUserManager.exists(userId)) return null;
3439        flags = updateFlagsForPackage(flags, userId, packageName);
3440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3441                false /* requireFullPermission */, false /* checkShell */, "get package info");
3442
3443        // reader
3444        synchronized (mPackages) {
3445            // Normalize package name to handle renamed packages and static libs
3446            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3447
3448            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3449            if (matchFactoryOnly) {
3450                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3451                if (ps != null) {
3452                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3453                        return null;
3454                    }
3455                    return generatePackageInfo(ps, flags, userId);
3456                }
3457            }
3458
3459            PackageParser.Package p = mPackages.get(packageName);
3460            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3461                return null;
3462            }
3463            if (DEBUG_PACKAGE_INFO)
3464                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3465            if (p != null) {
3466                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3467                        Binder.getCallingUid(), userId)) {
3468                    return null;
3469                }
3470                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3471            }
3472            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3473                final PackageSetting ps = mSettings.mPackages.get(packageName);
3474                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3475                    return null;
3476                }
3477                return generatePackageInfo(ps, flags, userId);
3478            }
3479        }
3480        return null;
3481    }
3482
3483
3484    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3485        // System/shell/root get to see all static libs
3486        final int appId = UserHandle.getAppId(uid);
3487        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3488                || appId == Process.ROOT_UID) {
3489            return false;
3490        }
3491
3492        // No package means no static lib as it is always on internal storage
3493        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3494            return false;
3495        }
3496
3497        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3498                ps.pkg.staticSharedLibVersion);
3499        if (libEntry == null) {
3500            return false;
3501        }
3502
3503        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3504        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3505        if (uidPackageNames == null) {
3506            return true;
3507        }
3508
3509        for (String uidPackageName : uidPackageNames) {
3510            if (ps.name.equals(uidPackageName)) {
3511                return false;
3512            }
3513            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3514            if (uidPs != null) {
3515                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3516                        libEntry.info.getName());
3517                if (index < 0) {
3518                    continue;
3519                }
3520                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3521                    return false;
3522                }
3523            }
3524        }
3525        return true;
3526    }
3527
3528    @Override
3529    public String[] currentToCanonicalPackageNames(String[] names) {
3530        String[] out = new String[names.length];
3531        // reader
3532        synchronized (mPackages) {
3533            for (int i=names.length-1; i>=0; i--) {
3534                PackageSetting ps = mSettings.mPackages.get(names[i]);
3535                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3536            }
3537        }
3538        return out;
3539    }
3540
3541    @Override
3542    public String[] canonicalToCurrentPackageNames(String[] names) {
3543        String[] out = new String[names.length];
3544        // reader
3545        synchronized (mPackages) {
3546            for (int i=names.length-1; i>=0; i--) {
3547                String cur = mSettings.getRenamedPackageLPr(names[i]);
3548                out[i] = cur != null ? cur : names[i];
3549            }
3550        }
3551        return out;
3552    }
3553
3554    @Override
3555    public int getPackageUid(String packageName, int flags, int userId) {
3556        if (!sUserManager.exists(userId)) return -1;
3557        flags = updateFlagsForPackage(flags, userId, packageName);
3558        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3559                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3560
3561        // reader
3562        synchronized (mPackages) {
3563            final PackageParser.Package p = mPackages.get(packageName);
3564            if (p != null && p.isMatch(flags)) {
3565                return UserHandle.getUid(userId, p.applicationInfo.uid);
3566            }
3567            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3568                final PackageSetting ps = mSettings.mPackages.get(packageName);
3569                if (ps != null && ps.isMatch(flags)) {
3570                    return UserHandle.getUid(userId, ps.appId);
3571                }
3572            }
3573        }
3574
3575        return -1;
3576    }
3577
3578    @Override
3579    public int[] getPackageGids(String packageName, int flags, int userId) {
3580        if (!sUserManager.exists(userId)) return null;
3581        flags = updateFlagsForPackage(flags, userId, packageName);
3582        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3583                false /* requireFullPermission */, false /* checkShell */,
3584                "getPackageGids");
3585
3586        // reader
3587        synchronized (mPackages) {
3588            final PackageParser.Package p = mPackages.get(packageName);
3589            if (p != null && p.isMatch(flags)) {
3590                PackageSetting ps = (PackageSetting) p.mExtras;
3591                // TODO: Shouldn't this be checking for package installed state for userId and
3592                // return null?
3593                return ps.getPermissionsState().computeGids(userId);
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 ps.getPermissionsState().computeGids(userId);
3599                }
3600            }
3601        }
3602
3603        return null;
3604    }
3605
3606    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3607        if (bp.perm != null) {
3608            return PackageParser.generatePermissionInfo(bp.perm, flags);
3609        }
3610        PermissionInfo pi = new PermissionInfo();
3611        pi.name = bp.name;
3612        pi.packageName = bp.sourcePackage;
3613        pi.nonLocalizedLabel = bp.name;
3614        pi.protectionLevel = bp.protectionLevel;
3615        return pi;
3616    }
3617
3618    @Override
3619    public PermissionInfo getPermissionInfo(String name, int flags) {
3620        // reader
3621        synchronized (mPackages) {
3622            final BasePermission p = mSettings.mPermissions.get(name);
3623            if (p != null) {
3624                return generatePermissionInfo(p, flags);
3625            }
3626            return null;
3627        }
3628    }
3629
3630    @Override
3631    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3632            int flags) {
3633        // reader
3634        synchronized (mPackages) {
3635            if (group != null && !mPermissionGroups.containsKey(group)) {
3636                // This is thrown as NameNotFoundException
3637                return null;
3638            }
3639
3640            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3641            for (BasePermission p : mSettings.mPermissions.values()) {
3642                if (group == null) {
3643                    if (p.perm == null || p.perm.info.group == null) {
3644                        out.add(generatePermissionInfo(p, flags));
3645                    }
3646                } else {
3647                    if (p.perm != null && group.equals(p.perm.info.group)) {
3648                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3649                    }
3650                }
3651            }
3652            return new ParceledListSlice<>(out);
3653        }
3654    }
3655
3656    @Override
3657    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3658        // reader
3659        synchronized (mPackages) {
3660            return PackageParser.generatePermissionGroupInfo(
3661                    mPermissionGroups.get(name), flags);
3662        }
3663    }
3664
3665    @Override
3666    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3667        // reader
3668        synchronized (mPackages) {
3669            final int N = mPermissionGroups.size();
3670            ArrayList<PermissionGroupInfo> out
3671                    = new ArrayList<PermissionGroupInfo>(N);
3672            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3673                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3674            }
3675            return new ParceledListSlice<>(out);
3676        }
3677    }
3678
3679    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3680            int uid, int userId) {
3681        if (!sUserManager.exists(userId)) return null;
3682        PackageSetting ps = mSettings.mPackages.get(packageName);
3683        if (ps != null) {
3684            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3685                return null;
3686            }
3687            if (ps.pkg == null) {
3688                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3689                if (pInfo != null) {
3690                    return pInfo.applicationInfo;
3691                }
3692                return null;
3693            }
3694            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3695                    ps.readUserState(userId), userId);
3696            if (ai != null) {
3697                rebaseEnabledOverlays(ai, userId);
3698                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3699            }
3700            return ai;
3701        }
3702        return null;
3703    }
3704
3705    @Override
3706    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3707        if (!sUserManager.exists(userId)) return null;
3708        flags = updateFlagsForApplication(flags, userId, packageName);
3709        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3710                false /* requireFullPermission */, false /* checkShell */, "get application info");
3711
3712        // writer
3713        synchronized (mPackages) {
3714            // Normalize package name to handle renamed packages and static libs
3715            packageName = resolveInternalPackageNameLPr(packageName,
3716                    PackageManager.VERSION_CODE_HIGHEST);
3717
3718            PackageParser.Package p = mPackages.get(packageName);
3719            if (DEBUG_PACKAGE_INFO) Log.v(
3720                    TAG, "getApplicationInfo " + packageName
3721                    + ": " + p);
3722            if (p != null) {
3723                PackageSetting ps = mSettings.mPackages.get(packageName);
3724                if (ps == null) return null;
3725                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3726                    return null;
3727                }
3728                // Note: isEnabledLP() does not apply here - always return info
3729                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3730                        p, flags, ps.readUserState(userId), userId);
3731                if (ai != null) {
3732                    rebaseEnabledOverlays(ai, userId);
3733                    ai.packageName = resolveExternalPackageNameLPr(p);
3734                }
3735                return ai;
3736            }
3737            if ("android".equals(packageName)||"system".equals(packageName)) {
3738                return mAndroidApplication;
3739            }
3740            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3741                // Already generates the external package name
3742                return generateApplicationInfoFromSettingsLPw(packageName,
3743                        Binder.getCallingUid(), flags, userId);
3744            }
3745        }
3746        return null;
3747    }
3748
3749    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3750        List<String> paths = new ArrayList<>();
3751        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3752            mEnabledOverlayPaths.get(userId);
3753        if (userSpecificOverlays != null) {
3754            if (!"android".equals(ai.packageName)) {
3755                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3756                if (frameworkOverlays != null) {
3757                    paths.addAll(frameworkOverlays);
3758                }
3759            }
3760
3761            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3762            if (appOverlays != null) {
3763                paths.addAll(appOverlays);
3764            }
3765        }
3766        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3767    }
3768
3769    private String normalizePackageNameLPr(String packageName) {
3770        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3771        return normalizedPackageName != null ? normalizedPackageName : packageName;
3772    }
3773
3774    @Override
3775    public void deletePreloadsFileCache() {
3776        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3777            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3778        }
3779        File dir = Environment.getDataPreloadsFileCacheDirectory();
3780        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3781        FileUtils.deleteContents(dir);
3782    }
3783
3784    @Override
3785    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3786            final IPackageDataObserver observer) {
3787        mContext.enforceCallingOrSelfPermission(
3788                android.Manifest.permission.CLEAR_APP_CACHE, null);
3789        mHandler.post(() -> {
3790            boolean success = false;
3791            try {
3792                freeStorage(volumeUuid, freeStorageSize, 0);
3793                success = true;
3794            } catch (IOException e) {
3795                Slog.w(TAG, e);
3796            }
3797            if (observer != null) {
3798                try {
3799                    observer.onRemoveCompleted(null, success);
3800                } catch (RemoteException e) {
3801                    Slog.w(TAG, e);
3802                }
3803            }
3804        });
3805    }
3806
3807    @Override
3808    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3809            final IntentSender pi) {
3810        mContext.enforceCallingOrSelfPermission(
3811                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3812        mHandler.post(() -> {
3813            boolean success = false;
3814            try {
3815                freeStorage(volumeUuid, freeStorageSize, 0);
3816                success = true;
3817            } catch (IOException e) {
3818                Slog.w(TAG, e);
3819            }
3820            if (pi != null) {
3821                try {
3822                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3823                } catch (SendIntentException e) {
3824                    Slog.w(TAG, e);
3825                }
3826            }
3827        });
3828    }
3829
3830    /**
3831     * Blocking call to clear various types of cached data across the system
3832     * until the requested bytes are available.
3833     */
3834    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3835        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3836        final File file = storage.findPathForUuid(volumeUuid);
3837        if (file.getUsableSpace() >= bytes) return;
3838
3839        if (ENABLE_FREE_CACHE_V2) {
3840            final boolean aggressive = (storageFlags
3841                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3842            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3843                    volumeUuid);
3844
3845            // 1. Pre-flight to determine if we have any chance to succeed
3846            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3847            if (internalVolume && (aggressive || SystemProperties
3848                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3849                deletePreloadsFileCache();
3850                if (file.getUsableSpace() >= bytes) return;
3851            }
3852
3853            // 3. Consider parsed APK data (aggressive only)
3854            if (internalVolume && aggressive) {
3855                FileUtils.deleteContents(mCacheDir);
3856                if (file.getUsableSpace() >= bytes) return;
3857            }
3858
3859            // 4. Consider cached app data (above quotas)
3860            try {
3861                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3862            } catch (InstallerException ignored) {
3863            }
3864            if (file.getUsableSpace() >= bytes) return;
3865
3866            // 5. Consider shared libraries with refcount=0 and age>2h
3867            // 6. Consider dexopt output (aggressive only)
3868            // 7. Consider ephemeral apps not used in last week
3869
3870            // 8. Consider cached app data (below quotas)
3871            try {
3872                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3873                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3874            } catch (InstallerException ignored) {
3875            }
3876            if (file.getUsableSpace() >= bytes) return;
3877
3878            // 9. Consider DropBox entries
3879            // 10. Consider ephemeral cookies
3880
3881        } else {
3882            try {
3883                mInstaller.freeCache(volumeUuid, bytes, 0);
3884            } catch (InstallerException ignored) {
3885            }
3886            if (file.getUsableSpace() >= bytes) return;
3887        }
3888
3889        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3890    }
3891
3892    /**
3893     * Update given flags based on encryption status of current user.
3894     */
3895    private int updateFlags(int flags, int userId) {
3896        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3897                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3898            // Caller expressed an explicit opinion about what encryption
3899            // aware/unaware components they want to see, so fall through and
3900            // give them what they want
3901        } else {
3902            // Caller expressed no opinion, so match based on user state
3903            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3904                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3905            } else {
3906                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3907            }
3908        }
3909        return flags;
3910    }
3911
3912    private UserManagerInternal getUserManagerInternal() {
3913        if (mUserManagerInternal == null) {
3914            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3915        }
3916        return mUserManagerInternal;
3917    }
3918
3919    private DeviceIdleController.LocalService getDeviceIdleController() {
3920        if (mDeviceIdleController == null) {
3921            mDeviceIdleController =
3922                    LocalServices.getService(DeviceIdleController.LocalService.class);
3923        }
3924        return mDeviceIdleController;
3925    }
3926
3927    /**
3928     * Update given flags when being used to request {@link PackageInfo}.
3929     */
3930    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3931        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3932        boolean triaged = true;
3933        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3934                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3935            // Caller is asking for component details, so they'd better be
3936            // asking for specific encryption matching behavior, or be triaged
3937            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3938                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3939                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3940                triaged = false;
3941            }
3942        }
3943        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3944                | PackageManager.MATCH_SYSTEM_ONLY
3945                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3946            triaged = false;
3947        }
3948        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3949            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3950                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3951                    + Debug.getCallers(5));
3952        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3953                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3954            // If the caller wants all packages and has a restricted profile associated with it,
3955            // then match all users. This is to make sure that launchers that need to access work
3956            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3957            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3958            flags |= PackageManager.MATCH_ANY_USER;
3959        }
3960        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3961            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3962                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3963        }
3964        return updateFlags(flags, userId);
3965    }
3966
3967    /**
3968     * Update given flags when being used to request {@link ApplicationInfo}.
3969     */
3970    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3971        return updateFlagsForPackage(flags, userId, cookie);
3972    }
3973
3974    /**
3975     * Update given flags when being used to request {@link ComponentInfo}.
3976     */
3977    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3978        if (cookie instanceof Intent) {
3979            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3980                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3981            }
3982        }
3983
3984        boolean triaged = true;
3985        // Caller is asking for component details, so they'd better be
3986        // asking for specific encryption matching behavior, or be triaged
3987        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3988                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3989                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3990            triaged = false;
3991        }
3992        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3993            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3994                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3995        }
3996
3997        return updateFlags(flags, userId);
3998    }
3999
4000    /**
4001     * Update given intent when being used to request {@link ResolveInfo}.
4002     */
4003    private Intent updateIntentForResolve(Intent intent) {
4004        if (intent.getSelector() != null) {
4005            intent = intent.getSelector();
4006        }
4007        if (DEBUG_PREFERRED) {
4008            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4009        }
4010        return intent;
4011    }
4012
4013    /**
4014     * Update given flags when being used to request {@link ResolveInfo}.
4015     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4016     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4017     * flag set. However, this flag is only honoured in three circumstances:
4018     * <ul>
4019     * <li>when called from a system process</li>
4020     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4021     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4022     * action and a {@code android.intent.category.BROWSABLE} category</li>
4023     * </ul>
4024     */
4025    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4026        // Safe mode means we shouldn't match any third-party components
4027        if (mSafeMode) {
4028            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4029        }
4030        final int callingUid = Binder.getCallingUid();
4031        if (getInstantAppPackageName(callingUid) != null) {
4032            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4033            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4034            flags |= PackageManager.MATCH_INSTANT;
4035        } else {
4036            // Otherwise, prevent leaking ephemeral components
4037            final boolean isSpecialProcess =
4038                    callingUid == Process.SYSTEM_UID
4039                    || callingUid == Process.SHELL_UID
4040                    || callingUid == 0;
4041            final boolean allowMatchInstant =
4042                    (includeInstantApp
4043                            && Intent.ACTION_VIEW.equals(intent.getAction())
4044                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4045                            && hasWebURI(intent))
4046                    || isSpecialProcess
4047                    || mContext.checkCallingOrSelfPermission(
4048                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4049            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4050            if (!allowMatchInstant) {
4051                flags &= ~PackageManager.MATCH_INSTANT;
4052            }
4053        }
4054        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4055    }
4056
4057    @Override
4058    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4059        if (!sUserManager.exists(userId)) return null;
4060        flags = updateFlagsForComponent(flags, userId, component);
4061        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4062                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4063        synchronized (mPackages) {
4064            PackageParser.Activity a = mActivities.mActivities.get(component);
4065
4066            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4067            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4068                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4069                if (ps == null) return null;
4070                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4071                        userId);
4072            }
4073            if (mResolveComponentName.equals(component)) {
4074                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4075                        new PackageUserState(), userId);
4076            }
4077        }
4078        return null;
4079    }
4080
4081    @Override
4082    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4083            String resolvedType) {
4084        synchronized (mPackages) {
4085            if (component.equals(mResolveComponentName)) {
4086                // The resolver supports EVERYTHING!
4087                return true;
4088            }
4089            PackageParser.Activity a = mActivities.mActivities.get(component);
4090            if (a == null) {
4091                return false;
4092            }
4093            for (int i=0; i<a.intents.size(); i++) {
4094                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4095                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4096                    return true;
4097                }
4098            }
4099            return false;
4100        }
4101    }
4102
4103    @Override
4104    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4105        if (!sUserManager.exists(userId)) return null;
4106        flags = updateFlagsForComponent(flags, userId, component);
4107        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4108                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4109        synchronized (mPackages) {
4110            PackageParser.Activity a = mReceivers.mActivities.get(component);
4111            if (DEBUG_PACKAGE_INFO) Log.v(
4112                TAG, "getReceiverInfo " + component + ": " + a);
4113            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4115                if (ps == null) return null;
4116                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4117                        ps.readUserState(userId), userId);
4118                if (ri != null) {
4119                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4120                }
4121                return ri;
4122            }
4123        }
4124        return null;
4125    }
4126
4127    @Override
4128    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4129        if (!sUserManager.exists(userId)) return null;
4130        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4131
4132        flags = updateFlagsForPackage(flags, userId, null);
4133
4134        final boolean canSeeStaticLibraries =
4135                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4136                        == PERMISSION_GRANTED
4137                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4138                        == PERMISSION_GRANTED
4139                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4140                        == PERMISSION_GRANTED
4141                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4142                        == PERMISSION_GRANTED;
4143
4144        synchronized (mPackages) {
4145            List<SharedLibraryInfo> result = null;
4146
4147            final int libCount = mSharedLibraries.size();
4148            for (int i = 0; i < libCount; i++) {
4149                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4150                if (versionedLib == null) {
4151                    continue;
4152                }
4153
4154                final int versionCount = versionedLib.size();
4155                for (int j = 0; j < versionCount; j++) {
4156                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4157                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4158                        break;
4159                    }
4160                    final long identity = Binder.clearCallingIdentity();
4161                    try {
4162                        // TODO: We will change version code to long, so in the new API it is long
4163                        PackageInfo packageInfo = getPackageInfoVersioned(
4164                                libInfo.getDeclaringPackage(), flags, userId);
4165                        if (packageInfo == null) {
4166                            continue;
4167                        }
4168                    } finally {
4169                        Binder.restoreCallingIdentity(identity);
4170                    }
4171
4172                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4173                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4174                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4175
4176                    if (result == null) {
4177                        result = new ArrayList<>();
4178                    }
4179                    result.add(resLibInfo);
4180                }
4181            }
4182
4183            return result != null ? new ParceledListSlice<>(result) : null;
4184        }
4185    }
4186
4187    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4188            SharedLibraryInfo libInfo, int flags, int userId) {
4189        List<VersionedPackage> versionedPackages = null;
4190        final int packageCount = mSettings.mPackages.size();
4191        for (int i = 0; i < packageCount; i++) {
4192            PackageSetting ps = mSettings.mPackages.valueAt(i);
4193
4194            if (ps == null) {
4195                continue;
4196            }
4197
4198            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4199                continue;
4200            }
4201
4202            final String libName = libInfo.getName();
4203            if (libInfo.isStatic()) {
4204                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4205                if (libIdx < 0) {
4206                    continue;
4207                }
4208                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4209                    continue;
4210                }
4211                if (versionedPackages == null) {
4212                    versionedPackages = new ArrayList<>();
4213                }
4214                // If the dependent is a static shared lib, use the public package name
4215                String dependentPackageName = ps.name;
4216                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4217                    dependentPackageName = ps.pkg.manifestPackageName;
4218                }
4219                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4220            } else if (ps.pkg != null) {
4221                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4222                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4223                    if (versionedPackages == null) {
4224                        versionedPackages = new ArrayList<>();
4225                    }
4226                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4227                }
4228            }
4229        }
4230
4231        return versionedPackages;
4232    }
4233
4234    @Override
4235    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4236        if (!sUserManager.exists(userId)) return null;
4237        flags = updateFlagsForComponent(flags, userId, component);
4238        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4239                false /* requireFullPermission */, false /* checkShell */, "get service info");
4240        synchronized (mPackages) {
4241            PackageParser.Service s = mServices.mServices.get(component);
4242            if (DEBUG_PACKAGE_INFO) Log.v(
4243                TAG, "getServiceInfo " + component + ": " + s);
4244            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4245                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4246                if (ps == null) return null;
4247                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4248                        ps.readUserState(userId), userId);
4249                if (si != null) {
4250                    rebaseEnabledOverlays(si.applicationInfo, userId);
4251                }
4252                return si;
4253            }
4254        }
4255        return null;
4256    }
4257
4258    @Override
4259    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4260        if (!sUserManager.exists(userId)) return null;
4261        flags = updateFlagsForComponent(flags, userId, component);
4262        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4263                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4264        synchronized (mPackages) {
4265            PackageParser.Provider p = mProviders.mProviders.get(component);
4266            if (DEBUG_PACKAGE_INFO) Log.v(
4267                TAG, "getProviderInfo " + component + ": " + p);
4268            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4269                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4270                if (ps == null) return null;
4271                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4272                        ps.readUserState(userId), userId);
4273                if (pi != null) {
4274                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4275                }
4276                return pi;
4277            }
4278        }
4279        return null;
4280    }
4281
4282    @Override
4283    public String[] getSystemSharedLibraryNames() {
4284        synchronized (mPackages) {
4285            Set<String> libs = null;
4286            final int libCount = mSharedLibraries.size();
4287            for (int i = 0; i < libCount; i++) {
4288                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4289                if (versionedLib == null) {
4290                    continue;
4291                }
4292                final int versionCount = versionedLib.size();
4293                for (int j = 0; j < versionCount; j++) {
4294                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4295                    if (!libEntry.info.isStatic()) {
4296                        if (libs == null) {
4297                            libs = new ArraySet<>();
4298                        }
4299                        libs.add(libEntry.info.getName());
4300                        break;
4301                    }
4302                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4303                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4304                            UserHandle.getUserId(Binder.getCallingUid()))) {
4305                        if (libs == null) {
4306                            libs = new ArraySet<>();
4307                        }
4308                        libs.add(libEntry.info.getName());
4309                        break;
4310                    }
4311                }
4312            }
4313
4314            if (libs != null) {
4315                String[] libsArray = new String[libs.size()];
4316                libs.toArray(libsArray);
4317                return libsArray;
4318            }
4319
4320            return null;
4321        }
4322    }
4323
4324    @Override
4325    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4326        synchronized (mPackages) {
4327            return mServicesSystemSharedLibraryPackageName;
4328        }
4329    }
4330
4331    @Override
4332    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4333        synchronized (mPackages) {
4334            return mSharedSystemSharedLibraryPackageName;
4335        }
4336    }
4337
4338    private void updateSequenceNumberLP(String packageName, int[] userList) {
4339        for (int i = userList.length - 1; i >= 0; --i) {
4340            final int userId = userList[i];
4341            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4342            if (changedPackages == null) {
4343                changedPackages = new SparseArray<>();
4344                mChangedPackages.put(userId, changedPackages);
4345            }
4346            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4347            if (sequenceNumbers == null) {
4348                sequenceNumbers = new HashMap<>();
4349                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4350            }
4351            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4352            if (sequenceNumber != null) {
4353                changedPackages.remove(sequenceNumber);
4354            }
4355            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4356            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4357        }
4358        mChangedPackagesSequenceNumber++;
4359    }
4360
4361    @Override
4362    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4363        synchronized (mPackages) {
4364            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4365                return null;
4366            }
4367            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4368            if (changedPackages == null) {
4369                return null;
4370            }
4371            final List<String> packageNames =
4372                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4373            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4374                final String packageName = changedPackages.get(i);
4375                if (packageName != null) {
4376                    packageNames.add(packageName);
4377                }
4378            }
4379            return packageNames.isEmpty()
4380                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4381        }
4382    }
4383
4384    @Override
4385    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4386        ArrayList<FeatureInfo> res;
4387        synchronized (mAvailableFeatures) {
4388            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4389            res.addAll(mAvailableFeatures.values());
4390        }
4391        final FeatureInfo fi = new FeatureInfo();
4392        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4393                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4394        res.add(fi);
4395
4396        return new ParceledListSlice<>(res);
4397    }
4398
4399    @Override
4400    public boolean hasSystemFeature(String name, int version) {
4401        synchronized (mAvailableFeatures) {
4402            final FeatureInfo feat = mAvailableFeatures.get(name);
4403            if (feat == null) {
4404                return false;
4405            } else {
4406                return feat.version >= version;
4407            }
4408        }
4409    }
4410
4411    @Override
4412    public int checkPermission(String permName, String pkgName, int userId) {
4413        if (!sUserManager.exists(userId)) {
4414            return PackageManager.PERMISSION_DENIED;
4415        }
4416
4417        synchronized (mPackages) {
4418            final PackageParser.Package p = mPackages.get(pkgName);
4419            if (p != null && p.mExtras != null) {
4420                final PackageSetting ps = (PackageSetting) p.mExtras;
4421                final PermissionsState permissionsState = ps.getPermissionsState();
4422                if (permissionsState.hasPermission(permName, userId)) {
4423                    return PackageManager.PERMISSION_GRANTED;
4424                }
4425                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4426                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4427                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4428                    return PackageManager.PERMISSION_GRANTED;
4429                }
4430            }
4431        }
4432
4433        return PackageManager.PERMISSION_DENIED;
4434    }
4435
4436    @Override
4437    public int checkUidPermission(String permName, int uid) {
4438        final int userId = UserHandle.getUserId(uid);
4439
4440        if (!sUserManager.exists(userId)) {
4441            return PackageManager.PERMISSION_DENIED;
4442        }
4443
4444        synchronized (mPackages) {
4445            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4446            if (obj != null) {
4447                final SettingBase ps = (SettingBase) obj;
4448                final PermissionsState permissionsState = ps.getPermissionsState();
4449                if (permissionsState.hasPermission(permName, userId)) {
4450                    return PackageManager.PERMISSION_GRANTED;
4451                }
4452                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4453                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4454                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4455                    return PackageManager.PERMISSION_GRANTED;
4456                }
4457            } else {
4458                ArraySet<String> perms = mSystemPermissions.get(uid);
4459                if (perms != null) {
4460                    if (perms.contains(permName)) {
4461                        return PackageManager.PERMISSION_GRANTED;
4462                    }
4463                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4464                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4465                        return PackageManager.PERMISSION_GRANTED;
4466                    }
4467                }
4468            }
4469        }
4470
4471        return PackageManager.PERMISSION_DENIED;
4472    }
4473
4474    @Override
4475    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4476        if (UserHandle.getCallingUserId() != userId) {
4477            mContext.enforceCallingPermission(
4478                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4479                    "isPermissionRevokedByPolicy for user " + userId);
4480        }
4481
4482        if (checkPermission(permission, packageName, userId)
4483                == PackageManager.PERMISSION_GRANTED) {
4484            return false;
4485        }
4486
4487        final long identity = Binder.clearCallingIdentity();
4488        try {
4489            final int flags = getPermissionFlags(permission, packageName, userId);
4490            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4491        } finally {
4492            Binder.restoreCallingIdentity(identity);
4493        }
4494    }
4495
4496    @Override
4497    public String getPermissionControllerPackageName() {
4498        synchronized (mPackages) {
4499            return mRequiredInstallerPackage;
4500        }
4501    }
4502
4503    /**
4504     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4505     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4506     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4507     * @param message the message to log on security exception
4508     */
4509    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4510            boolean checkShell, String message) {
4511        if (userId < 0) {
4512            throw new IllegalArgumentException("Invalid userId " + userId);
4513        }
4514        if (checkShell) {
4515            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4516        }
4517        if (userId == UserHandle.getUserId(callingUid)) return;
4518        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4519            if (requireFullPermission) {
4520                mContext.enforceCallingOrSelfPermission(
4521                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4522            } else {
4523                try {
4524                    mContext.enforceCallingOrSelfPermission(
4525                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4526                } catch (SecurityException se) {
4527                    mContext.enforceCallingOrSelfPermission(
4528                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4529                }
4530            }
4531        }
4532    }
4533
4534    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4535        if (callingUid == Process.SHELL_UID) {
4536            if (userHandle >= 0
4537                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4538                throw new SecurityException("Shell does not have permission to access user "
4539                        + userHandle);
4540            } else if (userHandle < 0) {
4541                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4542                        + Debug.getCallers(3));
4543            }
4544        }
4545    }
4546
4547    private BasePermission findPermissionTreeLP(String permName) {
4548        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4549            if (permName.startsWith(bp.name) &&
4550                    permName.length() > bp.name.length() &&
4551                    permName.charAt(bp.name.length()) == '.') {
4552                return bp;
4553            }
4554        }
4555        return null;
4556    }
4557
4558    private BasePermission checkPermissionTreeLP(String permName) {
4559        if (permName != null) {
4560            BasePermission bp = findPermissionTreeLP(permName);
4561            if (bp != null) {
4562                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4563                    return bp;
4564                }
4565                throw new SecurityException("Calling uid "
4566                        + Binder.getCallingUid()
4567                        + " is not allowed to add to permission tree "
4568                        + bp.name + " owned by uid " + bp.uid);
4569            }
4570        }
4571        throw new SecurityException("No permission tree found for " + permName);
4572    }
4573
4574    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4575        if (s1 == null) {
4576            return s2 == null;
4577        }
4578        if (s2 == null) {
4579            return false;
4580        }
4581        if (s1.getClass() != s2.getClass()) {
4582            return false;
4583        }
4584        return s1.equals(s2);
4585    }
4586
4587    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4588        if (pi1.icon != pi2.icon) return false;
4589        if (pi1.logo != pi2.logo) return false;
4590        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4591        if (!compareStrings(pi1.name, pi2.name)) return false;
4592        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4593        // We'll take care of setting this one.
4594        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4595        // These are not currently stored in settings.
4596        //if (!compareStrings(pi1.group, pi2.group)) return false;
4597        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4598        //if (pi1.labelRes != pi2.labelRes) return false;
4599        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4600        return true;
4601    }
4602
4603    int permissionInfoFootprint(PermissionInfo info) {
4604        int size = info.name.length();
4605        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4606        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4607        return size;
4608    }
4609
4610    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4611        int size = 0;
4612        for (BasePermission perm : mSettings.mPermissions.values()) {
4613            if (perm.uid == tree.uid) {
4614                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4615            }
4616        }
4617        return size;
4618    }
4619
4620    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4621        // We calculate the max size of permissions defined by this uid and throw
4622        // if that plus the size of 'info' would exceed our stated maximum.
4623        if (tree.uid != Process.SYSTEM_UID) {
4624            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4625            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4626                throw new SecurityException("Permission tree size cap exceeded");
4627            }
4628        }
4629    }
4630
4631    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4632        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4633            throw new SecurityException("Label must be specified in permission");
4634        }
4635        BasePermission tree = checkPermissionTreeLP(info.name);
4636        BasePermission bp = mSettings.mPermissions.get(info.name);
4637        boolean added = bp == null;
4638        boolean changed = true;
4639        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4640        if (added) {
4641            enforcePermissionCapLocked(info, tree);
4642            bp = new BasePermission(info.name, tree.sourcePackage,
4643                    BasePermission.TYPE_DYNAMIC);
4644        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4645            throw new SecurityException(
4646                    "Not allowed to modify non-dynamic permission "
4647                    + info.name);
4648        } else {
4649            if (bp.protectionLevel == fixedLevel
4650                    && bp.perm.owner.equals(tree.perm.owner)
4651                    && bp.uid == tree.uid
4652                    && comparePermissionInfos(bp.perm.info, info)) {
4653                changed = false;
4654            }
4655        }
4656        bp.protectionLevel = fixedLevel;
4657        info = new PermissionInfo(info);
4658        info.protectionLevel = fixedLevel;
4659        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4660        bp.perm.info.packageName = tree.perm.info.packageName;
4661        bp.uid = tree.uid;
4662        if (added) {
4663            mSettings.mPermissions.put(info.name, bp);
4664        }
4665        if (changed) {
4666            if (!async) {
4667                mSettings.writeLPr();
4668            } else {
4669                scheduleWriteSettingsLocked();
4670            }
4671        }
4672        return added;
4673    }
4674
4675    @Override
4676    public boolean addPermission(PermissionInfo info) {
4677        synchronized (mPackages) {
4678            return addPermissionLocked(info, false);
4679        }
4680    }
4681
4682    @Override
4683    public boolean addPermissionAsync(PermissionInfo info) {
4684        synchronized (mPackages) {
4685            return addPermissionLocked(info, true);
4686        }
4687    }
4688
4689    @Override
4690    public void removePermission(String name) {
4691        synchronized (mPackages) {
4692            checkPermissionTreeLP(name);
4693            BasePermission bp = mSettings.mPermissions.get(name);
4694            if (bp != null) {
4695                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4696                    throw new SecurityException(
4697                            "Not allowed to modify non-dynamic permission "
4698                            + name);
4699                }
4700                mSettings.mPermissions.remove(name);
4701                mSettings.writeLPr();
4702            }
4703        }
4704    }
4705
4706    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4707            BasePermission bp) {
4708        int index = pkg.requestedPermissions.indexOf(bp.name);
4709        if (index == -1) {
4710            throw new SecurityException("Package " + pkg.packageName
4711                    + " has not requested permission " + bp.name);
4712        }
4713        if (!bp.isRuntime() && !bp.isDevelopment()) {
4714            throw new SecurityException("Permission " + bp.name
4715                    + " is not a changeable permission type");
4716        }
4717    }
4718
4719    @Override
4720    public void grantRuntimePermission(String packageName, String name, final int userId) {
4721        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4722    }
4723
4724    private void grantRuntimePermission(String packageName, String name, final int userId,
4725            boolean overridePolicy) {
4726        if (!sUserManager.exists(userId)) {
4727            Log.e(TAG, "No such user:" + userId);
4728            return;
4729        }
4730
4731        mContext.enforceCallingOrSelfPermission(
4732                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4733                "grantRuntimePermission");
4734
4735        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4736                true /* requireFullPermission */, true /* checkShell */,
4737                "grantRuntimePermission");
4738
4739        final int uid;
4740        final SettingBase sb;
4741
4742        synchronized (mPackages) {
4743            final PackageParser.Package pkg = mPackages.get(packageName);
4744            if (pkg == null) {
4745                throw new IllegalArgumentException("Unknown package: " + packageName);
4746            }
4747
4748            final BasePermission bp = mSettings.mPermissions.get(name);
4749            if (bp == null) {
4750                throw new IllegalArgumentException("Unknown permission: " + name);
4751            }
4752
4753            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4754
4755            // If a permission review is required for legacy apps we represent
4756            // their permissions as always granted runtime ones since we need
4757            // to keep the review required permission flag per user while an
4758            // install permission's state is shared across all users.
4759            if (mPermissionReviewRequired
4760                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4761                    && bp.isRuntime()) {
4762                return;
4763            }
4764
4765            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4766            sb = (SettingBase) pkg.mExtras;
4767            if (sb == null) {
4768                throw new IllegalArgumentException("Unknown package: " + packageName);
4769            }
4770
4771            final PermissionsState permissionsState = sb.getPermissionsState();
4772
4773            final int flags = permissionsState.getPermissionFlags(name, userId);
4774            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4775                throw new SecurityException("Cannot grant system fixed permission "
4776                        + name + " for package " + packageName);
4777            }
4778            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4779                throw new SecurityException("Cannot grant policy fixed permission "
4780                        + name + " for package " + packageName);
4781            }
4782
4783            if (bp.isDevelopment()) {
4784                // Development permissions must be handled specially, since they are not
4785                // normal runtime permissions.  For now they apply to all users.
4786                if (permissionsState.grantInstallPermission(bp) !=
4787                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4788                    scheduleWriteSettingsLocked();
4789                }
4790                return;
4791            }
4792
4793            final PackageSetting ps = mSettings.mPackages.get(packageName);
4794            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4795                throw new SecurityException("Cannot grant non-ephemeral permission"
4796                        + name + " for package " + packageName);
4797            }
4798
4799            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4800                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4801                return;
4802            }
4803
4804            final int result = permissionsState.grantRuntimePermission(bp, userId);
4805            switch (result) {
4806                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4807                    return;
4808                }
4809
4810                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4811                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4812                    mHandler.post(new Runnable() {
4813                        @Override
4814                        public void run() {
4815                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4816                        }
4817                    });
4818                }
4819                break;
4820            }
4821
4822            if (bp.isRuntime()) {
4823                logPermissionGranted(mContext, name, packageName);
4824            }
4825
4826            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4827
4828            // Not critical if that is lost - app has to request again.
4829            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4830        }
4831
4832        // Only need to do this if user is initialized. Otherwise it's a new user
4833        // and there are no processes running as the user yet and there's no need
4834        // to make an expensive call to remount processes for the changed permissions.
4835        if (READ_EXTERNAL_STORAGE.equals(name)
4836                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4837            final long token = Binder.clearCallingIdentity();
4838            try {
4839                if (sUserManager.isInitialized(userId)) {
4840                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4841                            StorageManagerInternal.class);
4842                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4843                }
4844            } finally {
4845                Binder.restoreCallingIdentity(token);
4846            }
4847        }
4848    }
4849
4850    @Override
4851    public void revokeRuntimePermission(String packageName, String name, int userId) {
4852        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4853    }
4854
4855    private void revokeRuntimePermission(String packageName, String name, int userId,
4856            boolean overridePolicy) {
4857        if (!sUserManager.exists(userId)) {
4858            Log.e(TAG, "No such user:" + userId);
4859            return;
4860        }
4861
4862        mContext.enforceCallingOrSelfPermission(
4863                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4864                "revokeRuntimePermission");
4865
4866        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4867                true /* requireFullPermission */, true /* checkShell */,
4868                "revokeRuntimePermission");
4869
4870        final int appId;
4871
4872        synchronized (mPackages) {
4873            final PackageParser.Package pkg = mPackages.get(packageName);
4874            if (pkg == null) {
4875                throw new IllegalArgumentException("Unknown package: " + packageName);
4876            }
4877
4878            final BasePermission bp = mSettings.mPermissions.get(name);
4879            if (bp == null) {
4880                throw new IllegalArgumentException("Unknown permission: " + name);
4881            }
4882
4883            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4884
4885            // If a permission review is required for legacy apps we represent
4886            // their permissions as always granted runtime ones since we need
4887            // to keep the review required permission flag per user while an
4888            // install permission's state is shared across all users.
4889            if (mPermissionReviewRequired
4890                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4891                    && bp.isRuntime()) {
4892                return;
4893            }
4894
4895            SettingBase sb = (SettingBase) pkg.mExtras;
4896            if (sb == null) {
4897                throw new IllegalArgumentException("Unknown package: " + packageName);
4898            }
4899
4900            final PermissionsState permissionsState = sb.getPermissionsState();
4901
4902            final int flags = permissionsState.getPermissionFlags(name, userId);
4903            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4904                throw new SecurityException("Cannot revoke system fixed permission "
4905                        + name + " for package " + packageName);
4906            }
4907            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4908                throw new SecurityException("Cannot revoke policy fixed permission "
4909                        + name + " for package " + packageName);
4910            }
4911
4912            if (bp.isDevelopment()) {
4913                // Development permissions must be handled specially, since they are not
4914                // normal runtime permissions.  For now they apply to all users.
4915                if (permissionsState.revokeInstallPermission(bp) !=
4916                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4917                    scheduleWriteSettingsLocked();
4918                }
4919                return;
4920            }
4921
4922            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4923                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4924                return;
4925            }
4926
4927            if (bp.isRuntime()) {
4928                logPermissionRevoked(mContext, name, packageName);
4929            }
4930
4931            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4932
4933            // Critical, after this call app should never have the permission.
4934            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4935
4936            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4937        }
4938
4939        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4940    }
4941
4942    /**
4943     * Get the first event id for the permission.
4944     *
4945     * <p>There are four events for each permission: <ul>
4946     *     <li>Request permission: first id + 0</li>
4947     *     <li>Grant permission: first id + 1</li>
4948     *     <li>Request for permission denied: first id + 2</li>
4949     *     <li>Revoke permission: first id + 3</li>
4950     * </ul></p>
4951     *
4952     * @param name name of the permission
4953     *
4954     * @return The first event id for the permission
4955     */
4956    private static int getBaseEventId(@NonNull String name) {
4957        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4958
4959        if (eventIdIndex == -1) {
4960            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4961                    || "user".equals(Build.TYPE)) {
4962                Log.i(TAG, "Unknown permission " + name);
4963
4964                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4965            } else {
4966                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4967                //
4968                // Also update
4969                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4970                // - metrics_constants.proto
4971                throw new IllegalStateException("Unknown permission " + name);
4972            }
4973        }
4974
4975        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4976    }
4977
4978    /**
4979     * Log that a permission was revoked.
4980     *
4981     * @param context Context of the caller
4982     * @param name name of the permission
4983     * @param packageName package permission if for
4984     */
4985    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4986            @NonNull String packageName) {
4987        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4988    }
4989
4990    /**
4991     * Log that a permission request was granted.
4992     *
4993     * @param context Context of the caller
4994     * @param name name of the permission
4995     * @param packageName package permission if for
4996     */
4997    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4998            @NonNull String packageName) {
4999        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5000    }
5001
5002    @Override
5003    public void resetRuntimePermissions() {
5004        mContext.enforceCallingOrSelfPermission(
5005                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5006                "revokeRuntimePermission");
5007
5008        int callingUid = Binder.getCallingUid();
5009        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5010            mContext.enforceCallingOrSelfPermission(
5011                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5012                    "resetRuntimePermissions");
5013        }
5014
5015        synchronized (mPackages) {
5016            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5017            for (int userId : UserManagerService.getInstance().getUserIds()) {
5018                final int packageCount = mPackages.size();
5019                for (int i = 0; i < packageCount; i++) {
5020                    PackageParser.Package pkg = mPackages.valueAt(i);
5021                    if (!(pkg.mExtras instanceof PackageSetting)) {
5022                        continue;
5023                    }
5024                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5025                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5026                }
5027            }
5028        }
5029    }
5030
5031    @Override
5032    public int getPermissionFlags(String name, String packageName, int userId) {
5033        if (!sUserManager.exists(userId)) {
5034            return 0;
5035        }
5036
5037        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5038
5039        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5040                true /* requireFullPermission */, false /* checkShell */,
5041                "getPermissionFlags");
5042
5043        synchronized (mPackages) {
5044            final PackageParser.Package pkg = mPackages.get(packageName);
5045            if (pkg == null) {
5046                return 0;
5047            }
5048
5049            final BasePermission bp = mSettings.mPermissions.get(name);
5050            if (bp == null) {
5051                return 0;
5052            }
5053
5054            SettingBase sb = (SettingBase) pkg.mExtras;
5055            if (sb == null) {
5056                return 0;
5057            }
5058
5059            PermissionsState permissionsState = sb.getPermissionsState();
5060            return permissionsState.getPermissionFlags(name, userId);
5061        }
5062    }
5063
5064    @Override
5065    public void updatePermissionFlags(String name, String packageName, int flagMask,
5066            int flagValues, int userId) {
5067        if (!sUserManager.exists(userId)) {
5068            return;
5069        }
5070
5071        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5072
5073        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5074                true /* requireFullPermission */, true /* checkShell */,
5075                "updatePermissionFlags");
5076
5077        // Only the system can change these flags and nothing else.
5078        if (getCallingUid() != Process.SYSTEM_UID) {
5079            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5080            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5081            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5082            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5083            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5084        }
5085
5086        synchronized (mPackages) {
5087            final PackageParser.Package pkg = mPackages.get(packageName);
5088            if (pkg == null) {
5089                throw new IllegalArgumentException("Unknown package: " + packageName);
5090            }
5091
5092            final BasePermission bp = mSettings.mPermissions.get(name);
5093            if (bp == null) {
5094                throw new IllegalArgumentException("Unknown permission: " + name);
5095            }
5096
5097            SettingBase sb = (SettingBase) pkg.mExtras;
5098            if (sb == null) {
5099                throw new IllegalArgumentException("Unknown package: " + packageName);
5100            }
5101
5102            PermissionsState permissionsState = sb.getPermissionsState();
5103
5104            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5105
5106            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5107                // Install and runtime permissions are stored in different places,
5108                // so figure out what permission changed and persist the change.
5109                if (permissionsState.getInstallPermissionState(name) != null) {
5110                    scheduleWriteSettingsLocked();
5111                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5112                        || hadState) {
5113                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5114                }
5115            }
5116        }
5117    }
5118
5119    /**
5120     * Update the permission flags for all packages and runtime permissions of a user in order
5121     * to allow device or profile owner to remove POLICY_FIXED.
5122     */
5123    @Override
5124    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5125        if (!sUserManager.exists(userId)) {
5126            return;
5127        }
5128
5129        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5130
5131        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5132                true /* requireFullPermission */, true /* checkShell */,
5133                "updatePermissionFlagsForAllApps");
5134
5135        // Only the system can change system fixed flags.
5136        if (getCallingUid() != Process.SYSTEM_UID) {
5137            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5138            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5139        }
5140
5141        synchronized (mPackages) {
5142            boolean changed = false;
5143            final int packageCount = mPackages.size();
5144            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5145                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5146                SettingBase sb = (SettingBase) pkg.mExtras;
5147                if (sb == null) {
5148                    continue;
5149                }
5150                PermissionsState permissionsState = sb.getPermissionsState();
5151                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5152                        userId, flagMask, flagValues);
5153            }
5154            if (changed) {
5155                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5156            }
5157        }
5158    }
5159
5160    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5161        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5162                != PackageManager.PERMISSION_GRANTED
5163            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5164                != PackageManager.PERMISSION_GRANTED) {
5165            throw new SecurityException(message + " requires "
5166                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5167                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5168        }
5169    }
5170
5171    @Override
5172    public boolean shouldShowRequestPermissionRationale(String permissionName,
5173            String packageName, int userId) {
5174        if (UserHandle.getCallingUserId() != userId) {
5175            mContext.enforceCallingPermission(
5176                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5177                    "canShowRequestPermissionRationale for user " + userId);
5178        }
5179
5180        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5181        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5182            return false;
5183        }
5184
5185        if (checkPermission(permissionName, packageName, userId)
5186                == PackageManager.PERMISSION_GRANTED) {
5187            return false;
5188        }
5189
5190        final int flags;
5191
5192        final long identity = Binder.clearCallingIdentity();
5193        try {
5194            flags = getPermissionFlags(permissionName,
5195                    packageName, userId);
5196        } finally {
5197            Binder.restoreCallingIdentity(identity);
5198        }
5199
5200        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5201                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5202                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5203
5204        if ((flags & fixedFlags) != 0) {
5205            return false;
5206        }
5207
5208        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5209    }
5210
5211    @Override
5212    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5213        mContext.enforceCallingOrSelfPermission(
5214                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5215                "addOnPermissionsChangeListener");
5216
5217        synchronized (mPackages) {
5218            mOnPermissionChangeListeners.addListenerLocked(listener);
5219        }
5220    }
5221
5222    @Override
5223    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5224        synchronized (mPackages) {
5225            mOnPermissionChangeListeners.removeListenerLocked(listener);
5226        }
5227    }
5228
5229    @Override
5230    public boolean isProtectedBroadcast(String actionName) {
5231        synchronized (mPackages) {
5232            if (mProtectedBroadcasts.contains(actionName)) {
5233                return true;
5234            } else if (actionName != null) {
5235                // TODO: remove these terrible hacks
5236                if (actionName.startsWith("android.net.netmon.lingerExpired")
5237                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5238                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5239                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5240                    return true;
5241                }
5242            }
5243        }
5244        return false;
5245    }
5246
5247    @Override
5248    public int checkSignatures(String pkg1, String pkg2) {
5249        synchronized (mPackages) {
5250            final PackageParser.Package p1 = mPackages.get(pkg1);
5251            final PackageParser.Package p2 = mPackages.get(pkg2);
5252            if (p1 == null || p1.mExtras == null
5253                    || p2 == null || p2.mExtras == null) {
5254                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5255            }
5256            return compareSignatures(p1.mSignatures, p2.mSignatures);
5257        }
5258    }
5259
5260    @Override
5261    public int checkUidSignatures(int uid1, int uid2) {
5262        // Map to base uids.
5263        uid1 = UserHandle.getAppId(uid1);
5264        uid2 = UserHandle.getAppId(uid2);
5265        // reader
5266        synchronized (mPackages) {
5267            Signature[] s1;
5268            Signature[] s2;
5269            Object obj = mSettings.getUserIdLPr(uid1);
5270            if (obj != null) {
5271                if (obj instanceof SharedUserSetting) {
5272                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5273                } else if (obj instanceof PackageSetting) {
5274                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5275                } else {
5276                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5277                }
5278            } else {
5279                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5280            }
5281            obj = mSettings.getUserIdLPr(uid2);
5282            if (obj != null) {
5283                if (obj instanceof SharedUserSetting) {
5284                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5285                } else if (obj instanceof PackageSetting) {
5286                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5287                } else {
5288                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5289                }
5290            } else {
5291                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5292            }
5293            return compareSignatures(s1, s2);
5294        }
5295    }
5296
5297    /**
5298     * This method should typically only be used when granting or revoking
5299     * permissions, since the app may immediately restart after this call.
5300     * <p>
5301     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5302     * guard your work against the app being relaunched.
5303     */
5304    private void killUid(int appId, int userId, String reason) {
5305        final long identity = Binder.clearCallingIdentity();
5306        try {
5307            IActivityManager am = ActivityManager.getService();
5308            if (am != null) {
5309                try {
5310                    am.killUid(appId, userId, reason);
5311                } catch (RemoteException e) {
5312                    /* ignore - same process */
5313                }
5314            }
5315        } finally {
5316            Binder.restoreCallingIdentity(identity);
5317        }
5318    }
5319
5320    /**
5321     * Compares two sets of signatures. Returns:
5322     * <br />
5323     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5324     * <br />
5325     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5326     * <br />
5327     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5328     * <br />
5329     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5330     * <br />
5331     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5332     */
5333    static int compareSignatures(Signature[] s1, Signature[] s2) {
5334        if (s1 == null) {
5335            return s2 == null
5336                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5337                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5338        }
5339
5340        if (s2 == null) {
5341            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5342        }
5343
5344        if (s1.length != s2.length) {
5345            return PackageManager.SIGNATURE_NO_MATCH;
5346        }
5347
5348        // Since both signature sets are of size 1, we can compare without HashSets.
5349        if (s1.length == 1) {
5350            return s1[0].equals(s2[0]) ?
5351                    PackageManager.SIGNATURE_MATCH :
5352                    PackageManager.SIGNATURE_NO_MATCH;
5353        }
5354
5355        ArraySet<Signature> set1 = new ArraySet<Signature>();
5356        for (Signature sig : s1) {
5357            set1.add(sig);
5358        }
5359        ArraySet<Signature> set2 = new ArraySet<Signature>();
5360        for (Signature sig : s2) {
5361            set2.add(sig);
5362        }
5363        // Make sure s2 contains all signatures in s1.
5364        if (set1.equals(set2)) {
5365            return PackageManager.SIGNATURE_MATCH;
5366        }
5367        return PackageManager.SIGNATURE_NO_MATCH;
5368    }
5369
5370    /**
5371     * If the database version for this type of package (internal storage or
5372     * external storage) is less than the version where package signatures
5373     * were updated, return true.
5374     */
5375    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5376        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5377        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5378    }
5379
5380    /**
5381     * Used for backward compatibility to make sure any packages with
5382     * certificate chains get upgraded to the new style. {@code existingSigs}
5383     * will be in the old format (since they were stored on disk from before the
5384     * system upgrade) and {@code scannedSigs} will be in the newer format.
5385     */
5386    private int compareSignaturesCompat(PackageSignatures existingSigs,
5387            PackageParser.Package scannedPkg) {
5388        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5389            return PackageManager.SIGNATURE_NO_MATCH;
5390        }
5391
5392        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5393        for (Signature sig : existingSigs.mSignatures) {
5394            existingSet.add(sig);
5395        }
5396        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5397        for (Signature sig : scannedPkg.mSignatures) {
5398            try {
5399                Signature[] chainSignatures = sig.getChainSignatures();
5400                for (Signature chainSig : chainSignatures) {
5401                    scannedCompatSet.add(chainSig);
5402                }
5403            } catch (CertificateEncodingException e) {
5404                scannedCompatSet.add(sig);
5405            }
5406        }
5407        /*
5408         * Make sure the expanded scanned set contains all signatures in the
5409         * existing one.
5410         */
5411        if (scannedCompatSet.equals(existingSet)) {
5412            // Migrate the old signatures to the new scheme.
5413            existingSigs.assignSignatures(scannedPkg.mSignatures);
5414            // The new KeySets will be re-added later in the scanning process.
5415            synchronized (mPackages) {
5416                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5417            }
5418            return PackageManager.SIGNATURE_MATCH;
5419        }
5420        return PackageManager.SIGNATURE_NO_MATCH;
5421    }
5422
5423    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5424        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5425        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5426    }
5427
5428    private int compareSignaturesRecover(PackageSignatures existingSigs,
5429            PackageParser.Package scannedPkg) {
5430        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5431            return PackageManager.SIGNATURE_NO_MATCH;
5432        }
5433
5434        String msg = null;
5435        try {
5436            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5437                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5438                        + scannedPkg.packageName);
5439                return PackageManager.SIGNATURE_MATCH;
5440            }
5441        } catch (CertificateException e) {
5442            msg = e.getMessage();
5443        }
5444
5445        logCriticalInfo(Log.INFO,
5446                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5447        return PackageManager.SIGNATURE_NO_MATCH;
5448    }
5449
5450    @Override
5451    public List<String> getAllPackages() {
5452        synchronized (mPackages) {
5453            return new ArrayList<String>(mPackages.keySet());
5454        }
5455    }
5456
5457    @Override
5458    public String[] getPackagesForUid(int uid) {
5459        final int userId = UserHandle.getUserId(uid);
5460        uid = UserHandle.getAppId(uid);
5461        // reader
5462        synchronized (mPackages) {
5463            Object obj = mSettings.getUserIdLPr(uid);
5464            if (obj instanceof SharedUserSetting) {
5465                final SharedUserSetting sus = (SharedUserSetting) obj;
5466                final int N = sus.packages.size();
5467                String[] res = new String[N];
5468                final Iterator<PackageSetting> it = sus.packages.iterator();
5469                int i = 0;
5470                while (it.hasNext()) {
5471                    PackageSetting ps = it.next();
5472                    if (ps.getInstalled(userId)) {
5473                        res[i++] = ps.name;
5474                    } else {
5475                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5476                    }
5477                }
5478                return res;
5479            } else if (obj instanceof PackageSetting) {
5480                final PackageSetting ps = (PackageSetting) obj;
5481                if (ps.getInstalled(userId)) {
5482                    return new String[]{ps.name};
5483                }
5484            }
5485        }
5486        return null;
5487    }
5488
5489    @Override
5490    public String getNameForUid(int uid) {
5491        // reader
5492        synchronized (mPackages) {
5493            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5494            if (obj instanceof SharedUserSetting) {
5495                final SharedUserSetting sus = (SharedUserSetting) obj;
5496                return sus.name + ":" + sus.userId;
5497            } else if (obj instanceof PackageSetting) {
5498                final PackageSetting ps = (PackageSetting) obj;
5499                return ps.name;
5500            }
5501        }
5502        return null;
5503    }
5504
5505    @Override
5506    public int getUidForSharedUser(String sharedUserName) {
5507        if(sharedUserName == null) {
5508            return -1;
5509        }
5510        // reader
5511        synchronized (mPackages) {
5512            SharedUserSetting suid;
5513            try {
5514                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5515                if (suid != null) {
5516                    return suid.userId;
5517                }
5518            } catch (PackageManagerException ignore) {
5519                // can't happen, but, still need to catch it
5520            }
5521            return -1;
5522        }
5523    }
5524
5525    @Override
5526    public int getFlagsForUid(int uid) {
5527        synchronized (mPackages) {
5528            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5529            if (obj instanceof SharedUserSetting) {
5530                final SharedUserSetting sus = (SharedUserSetting) obj;
5531                return sus.pkgFlags;
5532            } else if (obj instanceof PackageSetting) {
5533                final PackageSetting ps = (PackageSetting) obj;
5534                return ps.pkgFlags;
5535            }
5536        }
5537        return 0;
5538    }
5539
5540    @Override
5541    public int getPrivateFlagsForUid(int uid) {
5542        synchronized (mPackages) {
5543            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5544            if (obj instanceof SharedUserSetting) {
5545                final SharedUserSetting sus = (SharedUserSetting) obj;
5546                return sus.pkgPrivateFlags;
5547            } else if (obj instanceof PackageSetting) {
5548                final PackageSetting ps = (PackageSetting) obj;
5549                return ps.pkgPrivateFlags;
5550            }
5551        }
5552        return 0;
5553    }
5554
5555    @Override
5556    public boolean isUidPrivileged(int uid) {
5557        uid = UserHandle.getAppId(uid);
5558        // reader
5559        synchronized (mPackages) {
5560            Object obj = mSettings.getUserIdLPr(uid);
5561            if (obj instanceof SharedUserSetting) {
5562                final SharedUserSetting sus = (SharedUserSetting) obj;
5563                final Iterator<PackageSetting> it = sus.packages.iterator();
5564                while (it.hasNext()) {
5565                    if (it.next().isPrivileged()) {
5566                        return true;
5567                    }
5568                }
5569            } else if (obj instanceof PackageSetting) {
5570                final PackageSetting ps = (PackageSetting) obj;
5571                return ps.isPrivileged();
5572            }
5573        }
5574        return false;
5575    }
5576
5577    @Override
5578    public String[] getAppOpPermissionPackages(String permissionName) {
5579        synchronized (mPackages) {
5580            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5581            if (pkgs == null) {
5582                return null;
5583            }
5584            return pkgs.toArray(new String[pkgs.size()]);
5585        }
5586    }
5587
5588    @Override
5589    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5590            int flags, int userId) {
5591        return resolveIntentInternal(
5592                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5593    }
5594
5595    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5596            int flags, int userId, boolean includeInstantApp) {
5597        try {
5598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5599
5600            if (!sUserManager.exists(userId)) return null;
5601            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5602            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5603                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5604
5605            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5606            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5607                    flags, userId, includeInstantApp);
5608            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5609
5610            final ResolveInfo bestChoice =
5611                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5612            return bestChoice;
5613        } finally {
5614            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5615        }
5616    }
5617
5618    @Override
5619    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5620        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5621            throw new SecurityException(
5622                    "findPersistentPreferredActivity can only be run by the system");
5623        }
5624        if (!sUserManager.exists(userId)) {
5625            return null;
5626        }
5627        intent = updateIntentForResolve(intent);
5628        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5629        final int flags = updateFlagsForResolve(0, userId, intent, false);
5630        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5631                userId);
5632        synchronized (mPackages) {
5633            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5634                    userId);
5635        }
5636    }
5637
5638    @Override
5639    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5640            IntentFilter filter, int match, ComponentName activity) {
5641        final int userId = UserHandle.getCallingUserId();
5642        if (DEBUG_PREFERRED) {
5643            Log.v(TAG, "setLastChosenActivity intent=" + intent
5644                + " resolvedType=" + resolvedType
5645                + " flags=" + flags
5646                + " filter=" + filter
5647                + " match=" + match
5648                + " activity=" + activity);
5649            filter.dump(new PrintStreamPrinter(System.out), "    ");
5650        }
5651        intent.setComponent(null);
5652        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5653                userId);
5654        // Find any earlier preferred or last chosen entries and nuke them
5655        findPreferredActivity(intent, resolvedType,
5656                flags, query, 0, false, true, false, userId);
5657        // Add the new activity as the last chosen for this filter
5658        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5659                "Setting last chosen");
5660    }
5661
5662    @Override
5663    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5664        final int userId = UserHandle.getCallingUserId();
5665        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5666        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5667                userId);
5668        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5669                false, false, false, userId);
5670    }
5671
5672    /**
5673     * Returns whether or not instant apps have been disabled remotely.
5674     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5675     * held. Otherwise we run the risk of deadlock.
5676     */
5677    private boolean isEphemeralDisabled() {
5678        // ephemeral apps have been disabled across the board
5679        if (DISABLE_EPHEMERAL_APPS) {
5680            return true;
5681        }
5682        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5683        if (!mSystemReady) {
5684            return true;
5685        }
5686        // we can't get a content resolver until the system is ready; these checks must happen last
5687        final ContentResolver resolver = mContext.getContentResolver();
5688        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5689            return true;
5690        }
5691        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5692    }
5693
5694    private boolean isEphemeralAllowed(
5695            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5696            boolean skipPackageCheck) {
5697        final int callingUser = UserHandle.getCallingUserId();
5698        if (callingUser != UserHandle.USER_SYSTEM) {
5699            return false;
5700        }
5701        if (mInstantAppResolverConnection == null) {
5702            return false;
5703        }
5704        if (mInstantAppInstallerComponent == null) {
5705            return false;
5706        }
5707        if (intent.getComponent() != null) {
5708            return false;
5709        }
5710        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5711            return false;
5712        }
5713        if (!skipPackageCheck && intent.getPackage() != null) {
5714            return false;
5715        }
5716        final boolean isWebUri = hasWebURI(intent);
5717        if (!isWebUri || intent.getData().getHost() == null) {
5718            return false;
5719        }
5720        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5721        // Or if there's already an ephemeral app installed that handles the action
5722        synchronized (mPackages) {
5723            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5724            for (int n = 0; n < count; n++) {
5725                ResolveInfo info = resolvedActivities.get(n);
5726                String packageName = info.activityInfo.packageName;
5727                PackageSetting ps = mSettings.mPackages.get(packageName);
5728                if (ps != null) {
5729                    // Try to get the status from User settings first
5730                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5731                    int status = (int) (packedStatus >> 32);
5732                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5733                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5734                        if (DEBUG_EPHEMERAL) {
5735                            Slog.v(TAG, "DENY ephemeral apps;"
5736                                + " pkg: " + packageName + ", status: " + status);
5737                        }
5738                        return false;
5739                    }
5740                    if (ps.getInstantApp(userId)) {
5741                        if (DEBUG_EPHEMERAL) {
5742                            Slog.v(TAG, "DENY instant app installed;"
5743                                    + " pkg: " + packageName);
5744                        }
5745                        return false;
5746                    }
5747                }
5748            }
5749        }
5750        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5751        return true;
5752    }
5753
5754    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5755            Intent origIntent, String resolvedType, String callingPackage,
5756            int userId) {
5757        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5758                new InstantAppRequest(responseObj, origIntent, resolvedType,
5759                        callingPackage, userId));
5760        mHandler.sendMessage(msg);
5761    }
5762
5763    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5764            int flags, List<ResolveInfo> query, int userId) {
5765        if (query != null) {
5766            final int N = query.size();
5767            if (N == 1) {
5768                return query.get(0);
5769            } else if (N > 1) {
5770                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5771                // If there is more than one activity with the same priority,
5772                // then let the user decide between them.
5773                ResolveInfo r0 = query.get(0);
5774                ResolveInfo r1 = query.get(1);
5775                if (DEBUG_INTENT_MATCHING || debug) {
5776                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5777                            + r1.activityInfo.name + "=" + r1.priority);
5778                }
5779                // If the first activity has a higher priority, or a different
5780                // default, then it is always desirable to pick it.
5781                if (r0.priority != r1.priority
5782                        || r0.preferredOrder != r1.preferredOrder
5783                        || r0.isDefault != r1.isDefault) {
5784                    return query.get(0);
5785                }
5786                // If we have saved a preference for a preferred activity for
5787                // this Intent, use that.
5788                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5789                        flags, query, r0.priority, true, false, debug, userId);
5790                if (ri != null) {
5791                    return ri;
5792                }
5793                // If we have an ephemeral app, use it
5794                for (int i = 0; i < N; i++) {
5795                    ri = query.get(i);
5796                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5797                        return ri;
5798                    }
5799                }
5800                ri = new ResolveInfo(mResolveInfo);
5801                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5802                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5803                // If all of the options come from the same package, show the application's
5804                // label and icon instead of the generic resolver's.
5805                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5806                // and then throw away the ResolveInfo itself, meaning that the caller loses
5807                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5808                // a fallback for this case; we only set the target package's resources on
5809                // the ResolveInfo, not the ActivityInfo.
5810                final String intentPackage = intent.getPackage();
5811                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5812                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5813                    ri.resolvePackageName = intentPackage;
5814                    if (userNeedsBadging(userId)) {
5815                        ri.noResourceId = true;
5816                    } else {
5817                        ri.icon = appi.icon;
5818                    }
5819                    ri.iconResourceId = appi.icon;
5820                    ri.labelRes = appi.labelRes;
5821                }
5822                ri.activityInfo.applicationInfo = new ApplicationInfo(
5823                        ri.activityInfo.applicationInfo);
5824                if (userId != 0) {
5825                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5826                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5827                }
5828                // Make sure that the resolver is displayable in car mode
5829                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5830                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5831                return ri;
5832            }
5833        }
5834        return null;
5835    }
5836
5837    /**
5838     * Return true if the given list is not empty and all of its contents have
5839     * an activityInfo with the given package name.
5840     */
5841    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5842        if (ArrayUtils.isEmpty(list)) {
5843            return false;
5844        }
5845        for (int i = 0, N = list.size(); i < N; i++) {
5846            final ResolveInfo ri = list.get(i);
5847            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5848            if (ai == null || !packageName.equals(ai.packageName)) {
5849                return false;
5850            }
5851        }
5852        return true;
5853    }
5854
5855    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5856            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5857        final int N = query.size();
5858        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5859                .get(userId);
5860        // Get the list of persistent preferred activities that handle the intent
5861        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5862        List<PersistentPreferredActivity> pprefs = ppir != null
5863                ? ppir.queryIntent(intent, resolvedType,
5864                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5865                        userId)
5866                : null;
5867        if (pprefs != null && pprefs.size() > 0) {
5868            final int M = pprefs.size();
5869            for (int i=0; i<M; i++) {
5870                final PersistentPreferredActivity ppa = pprefs.get(i);
5871                if (DEBUG_PREFERRED || debug) {
5872                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5873                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5874                            + "\n  component=" + ppa.mComponent);
5875                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5876                }
5877                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5878                        flags | MATCH_DISABLED_COMPONENTS, userId);
5879                if (DEBUG_PREFERRED || debug) {
5880                    Slog.v(TAG, "Found persistent preferred activity:");
5881                    if (ai != null) {
5882                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5883                    } else {
5884                        Slog.v(TAG, "  null");
5885                    }
5886                }
5887                if (ai == null) {
5888                    // This previously registered persistent preferred activity
5889                    // component is no longer known. Ignore it and do NOT remove it.
5890                    continue;
5891                }
5892                for (int j=0; j<N; j++) {
5893                    final ResolveInfo ri = query.get(j);
5894                    if (!ri.activityInfo.applicationInfo.packageName
5895                            .equals(ai.applicationInfo.packageName)) {
5896                        continue;
5897                    }
5898                    if (!ri.activityInfo.name.equals(ai.name)) {
5899                        continue;
5900                    }
5901                    //  Found a persistent preference that can handle the intent.
5902                    if (DEBUG_PREFERRED || debug) {
5903                        Slog.v(TAG, "Returning persistent preferred activity: " +
5904                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5905                    }
5906                    return ri;
5907                }
5908            }
5909        }
5910        return null;
5911    }
5912
5913    // TODO: handle preferred activities missing while user has amnesia
5914    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5915            List<ResolveInfo> query, int priority, boolean always,
5916            boolean removeMatches, boolean debug, int userId) {
5917        if (!sUserManager.exists(userId)) return null;
5918        flags = updateFlagsForResolve(flags, userId, intent, false);
5919        intent = updateIntentForResolve(intent);
5920        // writer
5921        synchronized (mPackages) {
5922            // Try to find a matching persistent preferred activity.
5923            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5924                    debug, userId);
5925
5926            // If a persistent preferred activity matched, use it.
5927            if (pri != null) {
5928                return pri;
5929            }
5930
5931            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5932            // Get the list of preferred activities that handle the intent
5933            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5934            List<PreferredActivity> prefs = pir != null
5935                    ? pir.queryIntent(intent, resolvedType,
5936                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5937                            userId)
5938                    : null;
5939            if (prefs != null && prefs.size() > 0) {
5940                boolean changed = false;
5941                try {
5942                    // First figure out how good the original match set is.
5943                    // We will only allow preferred activities that came
5944                    // from the same match quality.
5945                    int match = 0;
5946
5947                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5948
5949                    final int N = query.size();
5950                    for (int j=0; j<N; j++) {
5951                        final ResolveInfo ri = query.get(j);
5952                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5953                                + ": 0x" + Integer.toHexString(match));
5954                        if (ri.match > match) {
5955                            match = ri.match;
5956                        }
5957                    }
5958
5959                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5960                            + Integer.toHexString(match));
5961
5962                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5963                    final int M = prefs.size();
5964                    for (int i=0; i<M; i++) {
5965                        final PreferredActivity pa = prefs.get(i);
5966                        if (DEBUG_PREFERRED || debug) {
5967                            Slog.v(TAG, "Checking PreferredActivity ds="
5968                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5969                                    + "\n  component=" + pa.mPref.mComponent);
5970                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5971                        }
5972                        if (pa.mPref.mMatch != match) {
5973                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5974                                    + Integer.toHexString(pa.mPref.mMatch));
5975                            continue;
5976                        }
5977                        // If it's not an "always" type preferred activity and that's what we're
5978                        // looking for, skip it.
5979                        if (always && !pa.mPref.mAlways) {
5980                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5981                            continue;
5982                        }
5983                        final ActivityInfo ai = getActivityInfo(
5984                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5985                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5986                                userId);
5987                        if (DEBUG_PREFERRED || debug) {
5988                            Slog.v(TAG, "Found preferred activity:");
5989                            if (ai != null) {
5990                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5991                            } else {
5992                                Slog.v(TAG, "  null");
5993                            }
5994                        }
5995                        if (ai == null) {
5996                            // This previously registered preferred activity
5997                            // component is no longer known.  Most likely an update
5998                            // to the app was installed and in the new version this
5999                            // component no longer exists.  Clean it up by removing
6000                            // it from the preferred activities list, and skip it.
6001                            Slog.w(TAG, "Removing dangling preferred activity: "
6002                                    + pa.mPref.mComponent);
6003                            pir.removeFilter(pa);
6004                            changed = true;
6005                            continue;
6006                        }
6007                        for (int j=0; j<N; j++) {
6008                            final ResolveInfo ri = query.get(j);
6009                            if (!ri.activityInfo.applicationInfo.packageName
6010                                    .equals(ai.applicationInfo.packageName)) {
6011                                continue;
6012                            }
6013                            if (!ri.activityInfo.name.equals(ai.name)) {
6014                                continue;
6015                            }
6016
6017                            if (removeMatches) {
6018                                pir.removeFilter(pa);
6019                                changed = true;
6020                                if (DEBUG_PREFERRED) {
6021                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6022                                }
6023                                break;
6024                            }
6025
6026                            // Okay we found a previously set preferred or last chosen app.
6027                            // If the result set is different from when this
6028                            // was created, we need to clear it and re-ask the
6029                            // user their preference, if we're looking for an "always" type entry.
6030                            if (always && !pa.mPref.sameSet(query)) {
6031                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6032                                        + intent + " type " + resolvedType);
6033                                if (DEBUG_PREFERRED) {
6034                                    Slog.v(TAG, "Removing preferred activity since set changed "
6035                                            + pa.mPref.mComponent);
6036                                }
6037                                pir.removeFilter(pa);
6038                                // Re-add the filter as a "last chosen" entry (!always)
6039                                PreferredActivity lastChosen = new PreferredActivity(
6040                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6041                                pir.addFilter(lastChosen);
6042                                changed = true;
6043                                return null;
6044                            }
6045
6046                            // Yay! Either the set matched or we're looking for the last chosen
6047                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6048                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6049                            return ri;
6050                        }
6051                    }
6052                } finally {
6053                    if (changed) {
6054                        if (DEBUG_PREFERRED) {
6055                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6056                        }
6057                        scheduleWritePackageRestrictionsLocked(userId);
6058                    }
6059                }
6060            }
6061        }
6062        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6063        return null;
6064    }
6065
6066    /*
6067     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6068     */
6069    @Override
6070    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6071            int targetUserId) {
6072        mContext.enforceCallingOrSelfPermission(
6073                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6074        List<CrossProfileIntentFilter> matches =
6075                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6076        if (matches != null) {
6077            int size = matches.size();
6078            for (int i = 0; i < size; i++) {
6079                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6080            }
6081        }
6082        if (hasWebURI(intent)) {
6083            // cross-profile app linking works only towards the parent.
6084            final UserInfo parent = getProfileParent(sourceUserId);
6085            synchronized(mPackages) {
6086                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6087                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6088                        intent, resolvedType, flags, sourceUserId, parent.id);
6089                return xpDomainInfo != null;
6090            }
6091        }
6092        return false;
6093    }
6094
6095    private UserInfo getProfileParent(int userId) {
6096        final long identity = Binder.clearCallingIdentity();
6097        try {
6098            return sUserManager.getProfileParent(userId);
6099        } finally {
6100            Binder.restoreCallingIdentity(identity);
6101        }
6102    }
6103
6104    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6105            String resolvedType, int userId) {
6106        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6107        if (resolver != null) {
6108            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6109        }
6110        return null;
6111    }
6112
6113    @Override
6114    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6115            String resolvedType, int flags, int userId) {
6116        try {
6117            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6118
6119            return new ParceledListSlice<>(
6120                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6121        } finally {
6122            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6123        }
6124    }
6125
6126    /**
6127     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6128     * instant, returns {@code null}.
6129     */
6130    private String getInstantAppPackageName(int callingUid) {
6131        // If the caller is an isolated app use the owner's uid for the lookup.
6132        if (Process.isIsolated(callingUid)) {
6133            callingUid = mIsolatedOwners.get(callingUid);
6134        }
6135        final int appId = UserHandle.getAppId(callingUid);
6136        synchronized (mPackages) {
6137            final Object obj = mSettings.getUserIdLPr(appId);
6138            if (obj instanceof PackageSetting) {
6139                final PackageSetting ps = (PackageSetting) obj;
6140                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6141                return isInstantApp ? ps.pkg.packageName : null;
6142            }
6143        }
6144        return null;
6145    }
6146
6147    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6148            String resolvedType, int flags, int userId) {
6149        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6150    }
6151
6152    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6153            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6154        if (!sUserManager.exists(userId)) return Collections.emptyList();
6155        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6156        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6158                false /* requireFullPermission */, false /* checkShell */,
6159                "query intent activities");
6160        ComponentName comp = intent.getComponent();
6161        if (comp == null) {
6162            if (intent.getSelector() != null) {
6163                intent = intent.getSelector();
6164                comp = intent.getComponent();
6165            }
6166        }
6167
6168        if (comp != null) {
6169            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6170            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6171            if (ai != null) {
6172                // When specifying an explicit component, we prevent the activity from being
6173                // used when either 1) the calling package is normal and the activity is within
6174                // an ephemeral application or 2) the calling package is ephemeral and the
6175                // activity is not visible to ephemeral applications.
6176                final boolean matchInstantApp =
6177                        (flags & PackageManager.MATCH_INSTANT) != 0;
6178                final boolean matchVisibleToInstantAppOnly =
6179                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6180                final boolean isCallerInstantApp =
6181                        instantAppPkgName != null;
6182                final boolean isTargetSameInstantApp =
6183                        comp.getPackageName().equals(instantAppPkgName);
6184                final boolean isTargetInstantApp =
6185                        (ai.applicationInfo.privateFlags
6186                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6187                final boolean isTargetHiddenFromInstantApp =
6188                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6189                final boolean blockResolution =
6190                        !isTargetSameInstantApp
6191                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6192                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6193                                        && isTargetHiddenFromInstantApp));
6194                if (!blockResolution) {
6195                    final ResolveInfo ri = new ResolveInfo();
6196                    ri.activityInfo = ai;
6197                    list.add(ri);
6198                }
6199            }
6200            return applyPostResolutionFilter(list, instantAppPkgName);
6201        }
6202
6203        // reader
6204        boolean sortResult = false;
6205        boolean addEphemeral = false;
6206        List<ResolveInfo> result;
6207        final String pkgName = intent.getPackage();
6208        final boolean ephemeralDisabled = isEphemeralDisabled();
6209        synchronized (mPackages) {
6210            if (pkgName == null) {
6211                List<CrossProfileIntentFilter> matchingFilters =
6212                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6213                // Check for results that need to skip the current profile.
6214                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6215                        resolvedType, flags, userId);
6216                if (xpResolveInfo != null) {
6217                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6218                    xpResult.add(xpResolveInfo);
6219                    return applyPostResolutionFilter(
6220                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6221                }
6222
6223                // Check for results in the current profile.
6224                result = filterIfNotSystemUser(mActivities.queryIntent(
6225                        intent, resolvedType, flags, userId), userId);
6226                addEphemeral = !ephemeralDisabled
6227                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6228                // Check for cross profile results.
6229                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6230                xpResolveInfo = queryCrossProfileIntents(
6231                        matchingFilters, intent, resolvedType, flags, userId,
6232                        hasNonNegativePriorityResult);
6233                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6234                    boolean isVisibleToUser = filterIfNotSystemUser(
6235                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6236                    if (isVisibleToUser) {
6237                        result.add(xpResolveInfo);
6238                        sortResult = true;
6239                    }
6240                }
6241                if (hasWebURI(intent)) {
6242                    CrossProfileDomainInfo xpDomainInfo = null;
6243                    final UserInfo parent = getProfileParent(userId);
6244                    if (parent != null) {
6245                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6246                                flags, userId, parent.id);
6247                    }
6248                    if (xpDomainInfo != null) {
6249                        if (xpResolveInfo != null) {
6250                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6251                            // in the result.
6252                            result.remove(xpResolveInfo);
6253                        }
6254                        if (result.size() == 0 && !addEphemeral) {
6255                            // No result in current profile, but found candidate in parent user.
6256                            // And we are not going to add emphemeral app, so we can return the
6257                            // result straight away.
6258                            result.add(xpDomainInfo.resolveInfo);
6259                            return applyPostResolutionFilter(result, instantAppPkgName);
6260                        }
6261                    } else if (result.size() <= 1 && !addEphemeral) {
6262                        // No result in parent user and <= 1 result in current profile, and we
6263                        // are not going to add emphemeral app, so we can return the result without
6264                        // further processing.
6265                        return applyPostResolutionFilter(result, instantAppPkgName);
6266                    }
6267                    // We have more than one candidate (combining results from current and parent
6268                    // profile), so we need filtering and sorting.
6269                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6270                            intent, flags, result, xpDomainInfo, userId);
6271                    sortResult = true;
6272                }
6273            } else {
6274                final PackageParser.Package pkg = mPackages.get(pkgName);
6275                if (pkg != null) {
6276                    return applyPostResolutionFilter(filterIfNotSystemUser(
6277                            mActivities.queryIntentForPackage(
6278                                    intent, resolvedType, flags, pkg.activities, userId),
6279                            userId), instantAppPkgName);
6280                } else {
6281                    // the caller wants to resolve for a particular package; however, there
6282                    // were no installed results, so, try to find an ephemeral result
6283                    addEphemeral = !ephemeralDisabled
6284                            && isEphemeralAllowed(
6285                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6286                    result = new ArrayList<ResolveInfo>();
6287                }
6288            }
6289        }
6290        if (addEphemeral) {
6291            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6292            final InstantAppRequest requestObject = new InstantAppRequest(
6293                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6294                    null /*callingPackage*/, userId);
6295            final AuxiliaryResolveInfo auxiliaryResponse =
6296                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6297                            mContext, mInstantAppResolverConnection, requestObject);
6298            if (auxiliaryResponse != null) {
6299                if (DEBUG_EPHEMERAL) {
6300                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6301                }
6302                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6303                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6304                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6305                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6306                // make sure this resolver is the default
6307                ephemeralInstaller.isDefault = true;
6308                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6309                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6310                // add a non-generic filter
6311                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6312                ephemeralInstaller.filter.addDataPath(
6313                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6314                ephemeralInstaller.instantAppAvailable = true;
6315                result.add(ephemeralInstaller);
6316            }
6317            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6318        }
6319        if (sortResult) {
6320            Collections.sort(result, mResolvePrioritySorter);
6321        }
6322        return applyPostResolutionFilter(result, instantAppPkgName);
6323    }
6324
6325    private static class CrossProfileDomainInfo {
6326        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6327        ResolveInfo resolveInfo;
6328        /* Best domain verification status of the activities found in the other profile */
6329        int bestDomainVerificationStatus;
6330    }
6331
6332    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6333            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6334        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6335                sourceUserId)) {
6336            return null;
6337        }
6338        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6339                resolvedType, flags, parentUserId);
6340
6341        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6342            return null;
6343        }
6344        CrossProfileDomainInfo result = null;
6345        int size = resultTargetUser.size();
6346        for (int i = 0; i < size; i++) {
6347            ResolveInfo riTargetUser = resultTargetUser.get(i);
6348            // Intent filter verification is only for filters that specify a host. So don't return
6349            // those that handle all web uris.
6350            if (riTargetUser.handleAllWebDataURI) {
6351                continue;
6352            }
6353            String packageName = riTargetUser.activityInfo.packageName;
6354            PackageSetting ps = mSettings.mPackages.get(packageName);
6355            if (ps == null) {
6356                continue;
6357            }
6358            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6359            int status = (int)(verificationState >> 32);
6360            if (result == null) {
6361                result = new CrossProfileDomainInfo();
6362                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6363                        sourceUserId, parentUserId);
6364                result.bestDomainVerificationStatus = status;
6365            } else {
6366                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6367                        result.bestDomainVerificationStatus);
6368            }
6369        }
6370        // Don't consider matches with status NEVER across profiles.
6371        if (result != null && result.bestDomainVerificationStatus
6372                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6373            return null;
6374        }
6375        return result;
6376    }
6377
6378    /**
6379     * Verification statuses are ordered from the worse to the best, except for
6380     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6381     */
6382    private int bestDomainVerificationStatus(int status1, int status2) {
6383        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6384            return status2;
6385        }
6386        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6387            return status1;
6388        }
6389        return (int) MathUtils.max(status1, status2);
6390    }
6391
6392    private boolean isUserEnabled(int userId) {
6393        long callingId = Binder.clearCallingIdentity();
6394        try {
6395            UserInfo userInfo = sUserManager.getUserInfo(userId);
6396            return userInfo != null && userInfo.isEnabled();
6397        } finally {
6398            Binder.restoreCallingIdentity(callingId);
6399        }
6400    }
6401
6402    /**
6403     * Filter out activities with systemUserOnly flag set, when current user is not System.
6404     *
6405     * @return filtered list
6406     */
6407    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6408        if (userId == UserHandle.USER_SYSTEM) {
6409            return resolveInfos;
6410        }
6411        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6412            ResolveInfo info = resolveInfos.get(i);
6413            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6414                resolveInfos.remove(i);
6415            }
6416        }
6417        return resolveInfos;
6418    }
6419
6420    /**
6421     * Filters out ephemeral activities.
6422     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6423     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6424     *
6425     * @param resolveInfos The pre-filtered list of resolved activities
6426     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6427     *          is performed.
6428     * @return A filtered list of resolved activities.
6429     */
6430    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6431            String ephemeralPkgName) {
6432        // TODO: When adding on-demand split support for non-instant apps, remove this check
6433        // and always apply post filtering
6434        if (ephemeralPkgName == null) {
6435            return resolveInfos;
6436        }
6437        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6438            final ResolveInfo info = resolveInfos.get(i);
6439            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6440            // allow activities that are defined in the provided package
6441            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6442                if (info.activityInfo.splitName != null
6443                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6444                                info.activityInfo.splitName)) {
6445                    // requested activity is defined in a split that hasn't been installed yet.
6446                    // add the installer to the resolve list
6447                    if (DEBUG_EPHEMERAL) {
6448                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6449                    }
6450                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6451                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6452                            info.activityInfo.packageName, info.activityInfo.splitName,
6453                            info.activityInfo.applicationInfo.versionCode);
6454                    // make sure this resolver is the default
6455                    installerInfo.isDefault = true;
6456                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6457                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6458                    // add a non-generic filter
6459                    installerInfo.filter = new IntentFilter();
6460                    // load resources from the correct package
6461                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6462                    resolveInfos.set(i, installerInfo);
6463                }
6464                continue;
6465            }
6466            // allow activities that have been explicitly exposed to ephemeral apps
6467            if (!isEphemeralApp
6468                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6469                continue;
6470            }
6471            resolveInfos.remove(i);
6472        }
6473        return resolveInfos;
6474    }
6475
6476    /**
6477     * @param resolveInfos list of resolve infos in descending priority order
6478     * @return if the list contains a resolve info with non-negative priority
6479     */
6480    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6481        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6482    }
6483
6484    private static boolean hasWebURI(Intent intent) {
6485        if (intent.getData() == null) {
6486            return false;
6487        }
6488        final String scheme = intent.getScheme();
6489        if (TextUtils.isEmpty(scheme)) {
6490            return false;
6491        }
6492        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6493    }
6494
6495    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6496            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6497            int userId) {
6498        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6499
6500        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6501            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6502                    candidates.size());
6503        }
6504
6505        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6506        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6507        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6508        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6509        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6510        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6511
6512        synchronized (mPackages) {
6513            final int count = candidates.size();
6514            // First, try to use linked apps. Partition the candidates into four lists:
6515            // one for the final results, one for the "do not use ever", one for "undefined status"
6516            // and finally one for "browser app type".
6517            for (int n=0; n<count; n++) {
6518                ResolveInfo info = candidates.get(n);
6519                String packageName = info.activityInfo.packageName;
6520                PackageSetting ps = mSettings.mPackages.get(packageName);
6521                if (ps != null) {
6522                    // Add to the special match all list (Browser use case)
6523                    if (info.handleAllWebDataURI) {
6524                        matchAllList.add(info);
6525                        continue;
6526                    }
6527                    // Try to get the status from User settings first
6528                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6529                    int status = (int)(packedStatus >> 32);
6530                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6531                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6532                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6533                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6534                                    + " : linkgen=" + linkGeneration);
6535                        }
6536                        // Use link-enabled generation as preferredOrder, i.e.
6537                        // prefer newly-enabled over earlier-enabled.
6538                        info.preferredOrder = linkGeneration;
6539                        alwaysList.add(info);
6540                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6541                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6542                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6543                        }
6544                        neverList.add(info);
6545                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6546                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6547                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6548                        }
6549                        alwaysAskList.add(info);
6550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6551                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6552                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6553                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6554                        }
6555                        undefinedList.add(info);
6556                    }
6557                }
6558            }
6559
6560            // We'll want to include browser possibilities in a few cases
6561            boolean includeBrowser = false;
6562
6563            // First try to add the "always" resolution(s) for the current user, if any
6564            if (alwaysList.size() > 0) {
6565                result.addAll(alwaysList);
6566            } else {
6567                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6568                result.addAll(undefinedList);
6569                // Maybe add one for the other profile.
6570                if (xpDomainInfo != null && (
6571                        xpDomainInfo.bestDomainVerificationStatus
6572                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6573                    result.add(xpDomainInfo.resolveInfo);
6574                }
6575                includeBrowser = true;
6576            }
6577
6578            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6579            // If there were 'always' entries their preferred order has been set, so we also
6580            // back that off to make the alternatives equivalent
6581            if (alwaysAskList.size() > 0) {
6582                for (ResolveInfo i : result) {
6583                    i.preferredOrder = 0;
6584                }
6585                result.addAll(alwaysAskList);
6586                includeBrowser = true;
6587            }
6588
6589            if (includeBrowser) {
6590                // Also add browsers (all of them or only the default one)
6591                if (DEBUG_DOMAIN_VERIFICATION) {
6592                    Slog.v(TAG, "   ...including browsers in candidate set");
6593                }
6594                if ((matchFlags & MATCH_ALL) != 0) {
6595                    result.addAll(matchAllList);
6596                } else {
6597                    // Browser/generic handling case.  If there's a default browser, go straight
6598                    // to that (but only if there is no other higher-priority match).
6599                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6600                    int maxMatchPrio = 0;
6601                    ResolveInfo defaultBrowserMatch = null;
6602                    final int numCandidates = matchAllList.size();
6603                    for (int n = 0; n < numCandidates; n++) {
6604                        ResolveInfo info = matchAllList.get(n);
6605                        // track the highest overall match priority...
6606                        if (info.priority > maxMatchPrio) {
6607                            maxMatchPrio = info.priority;
6608                        }
6609                        // ...and the highest-priority default browser match
6610                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6611                            if (defaultBrowserMatch == null
6612                                    || (defaultBrowserMatch.priority < info.priority)) {
6613                                if (debug) {
6614                                    Slog.v(TAG, "Considering default browser match " + info);
6615                                }
6616                                defaultBrowserMatch = info;
6617                            }
6618                        }
6619                    }
6620                    if (defaultBrowserMatch != null
6621                            && defaultBrowserMatch.priority >= maxMatchPrio
6622                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6623                    {
6624                        if (debug) {
6625                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6626                        }
6627                        result.add(defaultBrowserMatch);
6628                    } else {
6629                        result.addAll(matchAllList);
6630                    }
6631                }
6632
6633                // If there is nothing selected, add all candidates and remove the ones that the user
6634                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6635                if (result.size() == 0) {
6636                    result.addAll(candidates);
6637                    result.removeAll(neverList);
6638                }
6639            }
6640        }
6641        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6642            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6643                    result.size());
6644            for (ResolveInfo info : result) {
6645                Slog.v(TAG, "  + " + info.activityInfo);
6646            }
6647        }
6648        return result;
6649    }
6650
6651    // Returns a packed value as a long:
6652    //
6653    // high 'int'-sized word: link status: undefined/ask/never/always.
6654    // low 'int'-sized word: relative priority among 'always' results.
6655    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6656        long result = ps.getDomainVerificationStatusForUser(userId);
6657        // if none available, get the master status
6658        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6659            if (ps.getIntentFilterVerificationInfo() != null) {
6660                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6661            }
6662        }
6663        return result;
6664    }
6665
6666    private ResolveInfo querySkipCurrentProfileIntents(
6667            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6668            int flags, int sourceUserId) {
6669        if (matchingFilters != null) {
6670            int size = matchingFilters.size();
6671            for (int i = 0; i < size; i ++) {
6672                CrossProfileIntentFilter filter = matchingFilters.get(i);
6673                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6674                    // Checking if there are activities in the target user that can handle the
6675                    // intent.
6676                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6677                            resolvedType, flags, sourceUserId);
6678                    if (resolveInfo != null) {
6679                        return resolveInfo;
6680                    }
6681                }
6682            }
6683        }
6684        return null;
6685    }
6686
6687    // Return matching ResolveInfo in target user if any.
6688    private ResolveInfo queryCrossProfileIntents(
6689            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6690            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6691        if (matchingFilters != null) {
6692            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6693            // match the same intent. For performance reasons, it is better not to
6694            // run queryIntent twice for the same userId
6695            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6696            int size = matchingFilters.size();
6697            for (int i = 0; i < size; i++) {
6698                CrossProfileIntentFilter filter = matchingFilters.get(i);
6699                int targetUserId = filter.getTargetUserId();
6700                boolean skipCurrentProfile =
6701                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6702                boolean skipCurrentProfileIfNoMatchFound =
6703                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6704                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6705                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6706                    // Checking if there are activities in the target user that can handle the
6707                    // intent.
6708                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6709                            resolvedType, flags, sourceUserId);
6710                    if (resolveInfo != null) return resolveInfo;
6711                    alreadyTriedUserIds.put(targetUserId, true);
6712                }
6713            }
6714        }
6715        return null;
6716    }
6717
6718    /**
6719     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6720     * will forward the intent to the filter's target user.
6721     * Otherwise, returns null.
6722     */
6723    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6724            String resolvedType, int flags, int sourceUserId) {
6725        int targetUserId = filter.getTargetUserId();
6726        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6727                resolvedType, flags, targetUserId);
6728        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6729            // If all the matches in the target profile are suspended, return null.
6730            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6731                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6732                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6733                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6734                            targetUserId);
6735                }
6736            }
6737        }
6738        return null;
6739    }
6740
6741    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6742            int sourceUserId, int targetUserId) {
6743        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6744        long ident = Binder.clearCallingIdentity();
6745        boolean targetIsProfile;
6746        try {
6747            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6748        } finally {
6749            Binder.restoreCallingIdentity(ident);
6750        }
6751        String className;
6752        if (targetIsProfile) {
6753            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6754        } else {
6755            className = FORWARD_INTENT_TO_PARENT;
6756        }
6757        ComponentName forwardingActivityComponentName = new ComponentName(
6758                mAndroidApplication.packageName, className);
6759        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6760                sourceUserId);
6761        if (!targetIsProfile) {
6762            forwardingActivityInfo.showUserIcon = targetUserId;
6763            forwardingResolveInfo.noResourceId = true;
6764        }
6765        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6766        forwardingResolveInfo.priority = 0;
6767        forwardingResolveInfo.preferredOrder = 0;
6768        forwardingResolveInfo.match = 0;
6769        forwardingResolveInfo.isDefault = true;
6770        forwardingResolveInfo.filter = filter;
6771        forwardingResolveInfo.targetUserId = targetUserId;
6772        return forwardingResolveInfo;
6773    }
6774
6775    @Override
6776    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6777            Intent[] specifics, String[] specificTypes, Intent intent,
6778            String resolvedType, int flags, int userId) {
6779        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6780                specificTypes, intent, resolvedType, flags, userId));
6781    }
6782
6783    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6784            Intent[] specifics, String[] specificTypes, Intent intent,
6785            String resolvedType, int flags, int userId) {
6786        if (!sUserManager.exists(userId)) return Collections.emptyList();
6787        flags = updateFlagsForResolve(flags, userId, intent, false);
6788        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6789                false /* requireFullPermission */, false /* checkShell */,
6790                "query intent activity options");
6791        final String resultsAction = intent.getAction();
6792
6793        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6794                | PackageManager.GET_RESOLVED_FILTER, userId);
6795
6796        if (DEBUG_INTENT_MATCHING) {
6797            Log.v(TAG, "Query " + intent + ": " + results);
6798        }
6799
6800        int specificsPos = 0;
6801        int N;
6802
6803        // todo: note that the algorithm used here is O(N^2).  This
6804        // isn't a problem in our current environment, but if we start running
6805        // into situations where we have more than 5 or 10 matches then this
6806        // should probably be changed to something smarter...
6807
6808        // First we go through and resolve each of the specific items
6809        // that were supplied, taking care of removing any corresponding
6810        // duplicate items in the generic resolve list.
6811        if (specifics != null) {
6812            for (int i=0; i<specifics.length; i++) {
6813                final Intent sintent = specifics[i];
6814                if (sintent == null) {
6815                    continue;
6816                }
6817
6818                if (DEBUG_INTENT_MATCHING) {
6819                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6820                }
6821
6822                String action = sintent.getAction();
6823                if (resultsAction != null && resultsAction.equals(action)) {
6824                    // If this action was explicitly requested, then don't
6825                    // remove things that have it.
6826                    action = null;
6827                }
6828
6829                ResolveInfo ri = null;
6830                ActivityInfo ai = null;
6831
6832                ComponentName comp = sintent.getComponent();
6833                if (comp == null) {
6834                    ri = resolveIntent(
6835                        sintent,
6836                        specificTypes != null ? specificTypes[i] : null,
6837                            flags, userId);
6838                    if (ri == null) {
6839                        continue;
6840                    }
6841                    if (ri == mResolveInfo) {
6842                        // ACK!  Must do something better with this.
6843                    }
6844                    ai = ri.activityInfo;
6845                    comp = new ComponentName(ai.applicationInfo.packageName,
6846                            ai.name);
6847                } else {
6848                    ai = getActivityInfo(comp, flags, userId);
6849                    if (ai == null) {
6850                        continue;
6851                    }
6852                }
6853
6854                // Look for any generic query activities that are duplicates
6855                // of this specific one, and remove them from the results.
6856                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6857                N = results.size();
6858                int j;
6859                for (j=specificsPos; j<N; j++) {
6860                    ResolveInfo sri = results.get(j);
6861                    if ((sri.activityInfo.name.equals(comp.getClassName())
6862                            && sri.activityInfo.applicationInfo.packageName.equals(
6863                                    comp.getPackageName()))
6864                        || (action != null && sri.filter.matchAction(action))) {
6865                        results.remove(j);
6866                        if (DEBUG_INTENT_MATCHING) Log.v(
6867                            TAG, "Removing duplicate item from " + j
6868                            + " due to specific " + specificsPos);
6869                        if (ri == null) {
6870                            ri = sri;
6871                        }
6872                        j--;
6873                        N--;
6874                    }
6875                }
6876
6877                // Add this specific item to its proper place.
6878                if (ri == null) {
6879                    ri = new ResolveInfo();
6880                    ri.activityInfo = ai;
6881                }
6882                results.add(specificsPos, ri);
6883                ri.specificIndex = i;
6884                specificsPos++;
6885            }
6886        }
6887
6888        // Now we go through the remaining generic results and remove any
6889        // duplicate actions that are found here.
6890        N = results.size();
6891        for (int i=specificsPos; i<N-1; i++) {
6892            final ResolveInfo rii = results.get(i);
6893            if (rii.filter == null) {
6894                continue;
6895            }
6896
6897            // Iterate over all of the actions of this result's intent
6898            // filter...  typically this should be just one.
6899            final Iterator<String> it = rii.filter.actionsIterator();
6900            if (it == null) {
6901                continue;
6902            }
6903            while (it.hasNext()) {
6904                final String action = it.next();
6905                if (resultsAction != null && resultsAction.equals(action)) {
6906                    // If this action was explicitly requested, then don't
6907                    // remove things that have it.
6908                    continue;
6909                }
6910                for (int j=i+1; j<N; j++) {
6911                    final ResolveInfo rij = results.get(j);
6912                    if (rij.filter != null && rij.filter.hasAction(action)) {
6913                        results.remove(j);
6914                        if (DEBUG_INTENT_MATCHING) Log.v(
6915                            TAG, "Removing duplicate item from " + j
6916                            + " due to action " + action + " at " + i);
6917                        j--;
6918                        N--;
6919                    }
6920                }
6921            }
6922
6923            // If the caller didn't request filter information, drop it now
6924            // so we don't have to marshall/unmarshall it.
6925            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6926                rii.filter = null;
6927            }
6928        }
6929
6930        // Filter out the caller activity if so requested.
6931        if (caller != null) {
6932            N = results.size();
6933            for (int i=0; i<N; i++) {
6934                ActivityInfo ainfo = results.get(i).activityInfo;
6935                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6936                        && caller.getClassName().equals(ainfo.name)) {
6937                    results.remove(i);
6938                    break;
6939                }
6940            }
6941        }
6942
6943        // If the caller didn't request filter information,
6944        // drop them now so we don't have to
6945        // marshall/unmarshall it.
6946        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6947            N = results.size();
6948            for (int i=0; i<N; i++) {
6949                results.get(i).filter = null;
6950            }
6951        }
6952
6953        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6954        return results;
6955    }
6956
6957    @Override
6958    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6959            String resolvedType, int flags, int userId) {
6960        return new ParceledListSlice<>(
6961                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6962    }
6963
6964    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6965            String resolvedType, int flags, int userId) {
6966        if (!sUserManager.exists(userId)) return Collections.emptyList();
6967        flags = updateFlagsForResolve(flags, userId, intent, false);
6968        ComponentName comp = intent.getComponent();
6969        if (comp == null) {
6970            if (intent.getSelector() != null) {
6971                intent = intent.getSelector();
6972                comp = intent.getComponent();
6973            }
6974        }
6975        if (comp != null) {
6976            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6977            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6978            if (ai != null) {
6979                ResolveInfo ri = new ResolveInfo();
6980                ri.activityInfo = ai;
6981                list.add(ri);
6982            }
6983            return list;
6984        }
6985
6986        // reader
6987        synchronized (mPackages) {
6988            String pkgName = intent.getPackage();
6989            if (pkgName == null) {
6990                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6991            }
6992            final PackageParser.Package pkg = mPackages.get(pkgName);
6993            if (pkg != null) {
6994                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6995                        userId);
6996            }
6997            return Collections.emptyList();
6998        }
6999    }
7000
7001    @Override
7002    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7003        if (!sUserManager.exists(userId)) return null;
7004        flags = updateFlagsForResolve(flags, userId, intent, false);
7005        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7006        if (query != null) {
7007            if (query.size() >= 1) {
7008                // If there is more than one service with the same priority,
7009                // just arbitrarily pick the first one.
7010                return query.get(0);
7011            }
7012        }
7013        return null;
7014    }
7015
7016    @Override
7017    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7018            String resolvedType, int flags, int userId) {
7019        return new ParceledListSlice<>(
7020                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7021    }
7022
7023    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7024            String resolvedType, int flags, int userId) {
7025        if (!sUserManager.exists(userId)) return Collections.emptyList();
7026        flags = updateFlagsForResolve(flags, userId, intent, false);
7027        ComponentName comp = intent.getComponent();
7028        if (comp == null) {
7029            if (intent.getSelector() != null) {
7030                intent = intent.getSelector();
7031                comp = intent.getComponent();
7032            }
7033        }
7034        if (comp != null) {
7035            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7036            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7037            if (si != null) {
7038                final ResolveInfo ri = new ResolveInfo();
7039                ri.serviceInfo = si;
7040                list.add(ri);
7041            }
7042            return list;
7043        }
7044
7045        // reader
7046        synchronized (mPackages) {
7047            String pkgName = intent.getPackage();
7048            if (pkgName == null) {
7049                return mServices.queryIntent(intent, resolvedType, flags, userId);
7050            }
7051            final PackageParser.Package pkg = mPackages.get(pkgName);
7052            if (pkg != null) {
7053                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7054                        userId);
7055            }
7056            return Collections.emptyList();
7057        }
7058    }
7059
7060    @Override
7061    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7062            String resolvedType, int flags, int userId) {
7063        return new ParceledListSlice<>(
7064                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7065    }
7066
7067    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7068            Intent intent, String resolvedType, int flags, int userId) {
7069        if (!sUserManager.exists(userId)) return Collections.emptyList();
7070        flags = updateFlagsForResolve(flags, userId, intent, false);
7071        ComponentName comp = intent.getComponent();
7072        if (comp == null) {
7073            if (intent.getSelector() != null) {
7074                intent = intent.getSelector();
7075                comp = intent.getComponent();
7076            }
7077        }
7078        if (comp != null) {
7079            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7080            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7081            if (pi != null) {
7082                final ResolveInfo ri = new ResolveInfo();
7083                ri.providerInfo = pi;
7084                list.add(ri);
7085            }
7086            return list;
7087        }
7088
7089        // reader
7090        synchronized (mPackages) {
7091            String pkgName = intent.getPackage();
7092            if (pkgName == null) {
7093                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7094            }
7095            final PackageParser.Package pkg = mPackages.get(pkgName);
7096            if (pkg != null) {
7097                return mProviders.queryIntentForPackage(
7098                        intent, resolvedType, flags, pkg.providers, userId);
7099            }
7100            return Collections.emptyList();
7101        }
7102    }
7103
7104    @Override
7105    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7106        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7107        flags = updateFlagsForPackage(flags, userId, null);
7108        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7110                true /* requireFullPermission */, false /* checkShell */,
7111                "get installed packages");
7112
7113        // writer
7114        synchronized (mPackages) {
7115            ArrayList<PackageInfo> list;
7116            if (listUninstalled) {
7117                list = new ArrayList<>(mSettings.mPackages.size());
7118                for (PackageSetting ps : mSettings.mPackages.values()) {
7119                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7120                        continue;
7121                    }
7122                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7123                    if (pi != null) {
7124                        list.add(pi);
7125                    }
7126                }
7127            } else {
7128                list = new ArrayList<>(mPackages.size());
7129                for (PackageParser.Package p : mPackages.values()) {
7130                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7131                            Binder.getCallingUid(), userId)) {
7132                        continue;
7133                    }
7134                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7135                            p.mExtras, flags, userId);
7136                    if (pi != null) {
7137                        list.add(pi);
7138                    }
7139                }
7140            }
7141
7142            return new ParceledListSlice<>(list);
7143        }
7144    }
7145
7146    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7147            String[] permissions, boolean[] tmp, int flags, int userId) {
7148        int numMatch = 0;
7149        final PermissionsState permissionsState = ps.getPermissionsState();
7150        for (int i=0; i<permissions.length; i++) {
7151            final String permission = permissions[i];
7152            if (permissionsState.hasPermission(permission, userId)) {
7153                tmp[i] = true;
7154                numMatch++;
7155            } else {
7156                tmp[i] = false;
7157            }
7158        }
7159        if (numMatch == 0) {
7160            return;
7161        }
7162        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7163
7164        // The above might return null in cases of uninstalled apps or install-state
7165        // skew across users/profiles.
7166        if (pi != null) {
7167            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7168                if (numMatch == permissions.length) {
7169                    pi.requestedPermissions = permissions;
7170                } else {
7171                    pi.requestedPermissions = new String[numMatch];
7172                    numMatch = 0;
7173                    for (int i=0; i<permissions.length; i++) {
7174                        if (tmp[i]) {
7175                            pi.requestedPermissions[numMatch] = permissions[i];
7176                            numMatch++;
7177                        }
7178                    }
7179                }
7180            }
7181            list.add(pi);
7182        }
7183    }
7184
7185    @Override
7186    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7187            String[] permissions, int flags, int userId) {
7188        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7189        flags = updateFlagsForPackage(flags, userId, permissions);
7190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7191                true /* requireFullPermission */, false /* checkShell */,
7192                "get packages holding permissions");
7193        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7194
7195        // writer
7196        synchronized (mPackages) {
7197            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7198            boolean[] tmpBools = new boolean[permissions.length];
7199            if (listUninstalled) {
7200                for (PackageSetting ps : mSettings.mPackages.values()) {
7201                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7202                            userId);
7203                }
7204            } else {
7205                for (PackageParser.Package pkg : mPackages.values()) {
7206                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7207                    if (ps != null) {
7208                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7209                                userId);
7210                    }
7211                }
7212            }
7213
7214            return new ParceledListSlice<PackageInfo>(list);
7215        }
7216    }
7217
7218    @Override
7219    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7220        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7221        flags = updateFlagsForApplication(flags, userId, null);
7222        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7223
7224        // writer
7225        synchronized (mPackages) {
7226            ArrayList<ApplicationInfo> list;
7227            if (listUninstalled) {
7228                list = new ArrayList<>(mSettings.mPackages.size());
7229                for (PackageSetting ps : mSettings.mPackages.values()) {
7230                    ApplicationInfo ai;
7231                    int effectiveFlags = flags;
7232                    if (ps.isSystem()) {
7233                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7234                    }
7235                    if (ps.pkg != null) {
7236                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7237                            continue;
7238                        }
7239                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7240                                ps.readUserState(userId), userId);
7241                        if (ai != null) {
7242                            rebaseEnabledOverlays(ai, userId);
7243                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7244                        }
7245                    } else {
7246                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7247                        // and already converts to externally visible package name
7248                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7249                                Binder.getCallingUid(), effectiveFlags, userId);
7250                    }
7251                    if (ai != null) {
7252                        list.add(ai);
7253                    }
7254                }
7255            } else {
7256                list = new ArrayList<>(mPackages.size());
7257                for (PackageParser.Package p : mPackages.values()) {
7258                    if (p.mExtras != null) {
7259                        PackageSetting ps = (PackageSetting) p.mExtras;
7260                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7261                            continue;
7262                        }
7263                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7264                                ps.readUserState(userId), userId);
7265                        if (ai != null) {
7266                            rebaseEnabledOverlays(ai, userId);
7267                            ai.packageName = resolveExternalPackageNameLPr(p);
7268                            list.add(ai);
7269                        }
7270                    }
7271                }
7272            }
7273
7274            return new ParceledListSlice<>(list);
7275        }
7276    }
7277
7278    @Override
7279    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7280        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7281            return null;
7282        }
7283
7284        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7285                "getEphemeralApplications");
7286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7287                true /* requireFullPermission */, false /* checkShell */,
7288                "getEphemeralApplications");
7289        synchronized (mPackages) {
7290            List<InstantAppInfo> instantApps = mInstantAppRegistry
7291                    .getInstantAppsLPr(userId);
7292            if (instantApps != null) {
7293                return new ParceledListSlice<>(instantApps);
7294            }
7295        }
7296        return null;
7297    }
7298
7299    @Override
7300    public boolean isInstantApp(String packageName, int userId) {
7301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7302                true /* requireFullPermission */, false /* checkShell */,
7303                "isInstantApp");
7304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7305            return false;
7306        }
7307        int uid = Binder.getCallingUid();
7308        if (Process.isIsolated(uid)) {
7309            uid = mIsolatedOwners.get(uid);
7310        }
7311
7312        synchronized (mPackages) {
7313            final PackageSetting ps = mSettings.mPackages.get(packageName);
7314            PackageParser.Package pkg = mPackages.get(packageName);
7315            final boolean returnAllowed =
7316                    ps != null
7317                    && (isCallerSameApp(packageName, uid)
7318                            || mContext.checkCallingOrSelfPermission(
7319                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7320                                            == PERMISSION_GRANTED
7321                            || mInstantAppRegistry.isInstantAccessGranted(
7322                                    userId, UserHandle.getAppId(uid), ps.appId));
7323            if (returnAllowed) {
7324                return ps.getInstantApp(userId);
7325            }
7326        }
7327        return false;
7328    }
7329
7330    @Override
7331    public byte[] getInstantAppCookie(String packageName, int userId) {
7332        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7333            return null;
7334        }
7335
7336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7337                true /* requireFullPermission */, false /* checkShell */,
7338                "getInstantAppCookie");
7339        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7340            return null;
7341        }
7342        synchronized (mPackages) {
7343            return mInstantAppRegistry.getInstantAppCookieLPw(
7344                    packageName, userId);
7345        }
7346    }
7347
7348    @Override
7349    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7350        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7351            return true;
7352        }
7353
7354        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7355                true /* requireFullPermission */, true /* checkShell */,
7356                "setInstantAppCookie");
7357        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7358            return false;
7359        }
7360        synchronized (mPackages) {
7361            return mInstantAppRegistry.setInstantAppCookieLPw(
7362                    packageName, cookie, userId);
7363        }
7364    }
7365
7366    @Override
7367    public Bitmap getInstantAppIcon(String packageName, int userId) {
7368        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7369            return null;
7370        }
7371
7372        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7373                "getInstantAppIcon");
7374
7375        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7376                true /* requireFullPermission */, false /* checkShell */,
7377                "getInstantAppIcon");
7378
7379        synchronized (mPackages) {
7380            return mInstantAppRegistry.getInstantAppIconLPw(
7381                    packageName, userId);
7382        }
7383    }
7384
7385    private boolean isCallerSameApp(String packageName, int uid) {
7386        PackageParser.Package pkg = mPackages.get(packageName);
7387        return pkg != null
7388                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7389    }
7390
7391    @Override
7392    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7393        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7394    }
7395
7396    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7397        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7398
7399        // reader
7400        synchronized (mPackages) {
7401            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7402            final int userId = UserHandle.getCallingUserId();
7403            while (i.hasNext()) {
7404                final PackageParser.Package p = i.next();
7405                if (p.applicationInfo == null) continue;
7406
7407                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7408                        && !p.applicationInfo.isDirectBootAware();
7409                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7410                        && p.applicationInfo.isDirectBootAware();
7411
7412                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7413                        && (!mSafeMode || isSystemApp(p))
7414                        && (matchesUnaware || matchesAware)) {
7415                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7416                    if (ps != null) {
7417                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7418                                ps.readUserState(userId), userId);
7419                        if (ai != null) {
7420                            rebaseEnabledOverlays(ai, userId);
7421                            finalList.add(ai);
7422                        }
7423                    }
7424                }
7425            }
7426        }
7427
7428        return finalList;
7429    }
7430
7431    @Override
7432    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7433        if (!sUserManager.exists(userId)) return null;
7434        flags = updateFlagsForComponent(flags, userId, name);
7435        // reader
7436        synchronized (mPackages) {
7437            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7438            PackageSetting ps = provider != null
7439                    ? mSettings.mPackages.get(provider.owner.packageName)
7440                    : null;
7441            return ps != null
7442                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7443                    ? PackageParser.generateProviderInfo(provider, flags,
7444                            ps.readUserState(userId), userId)
7445                    : null;
7446        }
7447    }
7448
7449    /**
7450     * @deprecated
7451     */
7452    @Deprecated
7453    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7454        // reader
7455        synchronized (mPackages) {
7456            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7457                    .entrySet().iterator();
7458            final int userId = UserHandle.getCallingUserId();
7459            while (i.hasNext()) {
7460                Map.Entry<String, PackageParser.Provider> entry = i.next();
7461                PackageParser.Provider p = entry.getValue();
7462                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7463
7464                if (ps != null && p.syncable
7465                        && (!mSafeMode || (p.info.applicationInfo.flags
7466                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7467                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7468                            ps.readUserState(userId), userId);
7469                    if (info != null) {
7470                        outNames.add(entry.getKey());
7471                        outInfo.add(info);
7472                    }
7473                }
7474            }
7475        }
7476    }
7477
7478    @Override
7479    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7480            int uid, int flags, String metaDataKey) {
7481        final int userId = processName != null ? UserHandle.getUserId(uid)
7482                : UserHandle.getCallingUserId();
7483        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7484        flags = updateFlagsForComponent(flags, userId, processName);
7485
7486        ArrayList<ProviderInfo> finalList = null;
7487        // reader
7488        synchronized (mPackages) {
7489            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7490            while (i.hasNext()) {
7491                final PackageParser.Provider p = i.next();
7492                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7493                if (ps != null && p.info.authority != null
7494                        && (processName == null
7495                                || (p.info.processName.equals(processName)
7496                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7497                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7498
7499                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7500                    // parameter.
7501                    if (metaDataKey != null
7502                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7503                        continue;
7504                    }
7505
7506                    if (finalList == null) {
7507                        finalList = new ArrayList<ProviderInfo>(3);
7508                    }
7509                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7510                            ps.readUserState(userId), userId);
7511                    if (info != null) {
7512                        finalList.add(info);
7513                    }
7514                }
7515            }
7516        }
7517
7518        if (finalList != null) {
7519            Collections.sort(finalList, mProviderInitOrderSorter);
7520            return new ParceledListSlice<ProviderInfo>(finalList);
7521        }
7522
7523        return ParceledListSlice.emptyList();
7524    }
7525
7526    @Override
7527    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7528        // reader
7529        synchronized (mPackages) {
7530            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7531            return PackageParser.generateInstrumentationInfo(i, flags);
7532        }
7533    }
7534
7535    @Override
7536    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7537            String targetPackage, int flags) {
7538        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7539    }
7540
7541    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7542            int flags) {
7543        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7544
7545        // reader
7546        synchronized (mPackages) {
7547            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7548            while (i.hasNext()) {
7549                final PackageParser.Instrumentation p = i.next();
7550                if (targetPackage == null
7551                        || targetPackage.equals(p.info.targetPackage)) {
7552                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7553                            flags);
7554                    if (ii != null) {
7555                        finalList.add(ii);
7556                    }
7557                }
7558            }
7559        }
7560
7561        return finalList;
7562    }
7563
7564    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7565        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7566        try {
7567            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7568        } finally {
7569            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7570        }
7571    }
7572
7573    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7574        final File[] files = dir.listFiles();
7575        if (ArrayUtils.isEmpty(files)) {
7576            Log.d(TAG, "No files in app dir " + dir);
7577            return;
7578        }
7579
7580        if (DEBUG_PACKAGE_SCANNING) {
7581            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7582                    + " flags=0x" + Integer.toHexString(parseFlags));
7583        }
7584        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7585                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7586
7587        // Submit files for parsing in parallel
7588        int fileCount = 0;
7589        for (File file : files) {
7590            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7591                    && !PackageInstallerService.isStageName(file.getName());
7592            if (!isPackage) {
7593                // Ignore entries which are not packages
7594                continue;
7595            }
7596            parallelPackageParser.submit(file, parseFlags);
7597            fileCount++;
7598        }
7599
7600        // Process results one by one
7601        for (; fileCount > 0; fileCount--) {
7602            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7603            Throwable throwable = parseResult.throwable;
7604            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7605
7606            if (throwable == null) {
7607                // Static shared libraries have synthetic package names
7608                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7609                    renameStaticSharedLibraryPackage(parseResult.pkg);
7610                }
7611                try {
7612                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7613                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7614                                currentTime, null);
7615                    }
7616                } catch (PackageManagerException e) {
7617                    errorCode = e.error;
7618                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7619                }
7620            } else if (throwable instanceof PackageParser.PackageParserException) {
7621                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7622                        throwable;
7623                errorCode = e.error;
7624                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7625            } else {
7626                throw new IllegalStateException("Unexpected exception occurred while parsing "
7627                        + parseResult.scanFile, throwable);
7628            }
7629
7630            // Delete invalid userdata apps
7631            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7632                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7633                logCriticalInfo(Log.WARN,
7634                        "Deleting invalid package at " + parseResult.scanFile);
7635                removeCodePathLI(parseResult.scanFile);
7636            }
7637        }
7638        parallelPackageParser.close();
7639    }
7640
7641    private static File getSettingsProblemFile() {
7642        File dataDir = Environment.getDataDirectory();
7643        File systemDir = new File(dataDir, "system");
7644        File fname = new File(systemDir, "uiderrors.txt");
7645        return fname;
7646    }
7647
7648    static void reportSettingsProblem(int priority, String msg) {
7649        logCriticalInfo(priority, msg);
7650    }
7651
7652    public static void logCriticalInfo(int priority, String msg) {
7653        Slog.println(priority, TAG, msg);
7654        EventLogTags.writePmCriticalInfo(msg);
7655        try {
7656            File fname = getSettingsProblemFile();
7657            FileOutputStream out = new FileOutputStream(fname, true);
7658            PrintWriter pw = new FastPrintWriter(out);
7659            SimpleDateFormat formatter = new SimpleDateFormat();
7660            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7661            pw.println(dateString + ": " + msg);
7662            pw.close();
7663            FileUtils.setPermissions(
7664                    fname.toString(),
7665                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7666                    -1, -1);
7667        } catch (java.io.IOException e) {
7668        }
7669    }
7670
7671    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7672        if (srcFile.isDirectory()) {
7673            final File baseFile = new File(pkg.baseCodePath);
7674            long maxModifiedTime = baseFile.lastModified();
7675            if (pkg.splitCodePaths != null) {
7676                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7677                    final File splitFile = new File(pkg.splitCodePaths[i]);
7678                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7679                }
7680            }
7681            return maxModifiedTime;
7682        }
7683        return srcFile.lastModified();
7684    }
7685
7686    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7687            final int policyFlags) throws PackageManagerException {
7688        // When upgrading from pre-N MR1, verify the package time stamp using the package
7689        // directory and not the APK file.
7690        final long lastModifiedTime = mIsPreNMR1Upgrade
7691                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7692        if (ps != null
7693                && ps.codePath.equals(srcFile)
7694                && ps.timeStamp == lastModifiedTime
7695                && !isCompatSignatureUpdateNeeded(pkg)
7696                && !isRecoverSignatureUpdateNeeded(pkg)) {
7697            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7698            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7699            ArraySet<PublicKey> signingKs;
7700            synchronized (mPackages) {
7701                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7702            }
7703            if (ps.signatures.mSignatures != null
7704                    && ps.signatures.mSignatures.length != 0
7705                    && signingKs != null) {
7706                // Optimization: reuse the existing cached certificates
7707                // if the package appears to be unchanged.
7708                pkg.mSignatures = ps.signatures.mSignatures;
7709                pkg.mSigningKeys = signingKs;
7710                return;
7711            }
7712
7713            Slog.w(TAG, "PackageSetting for " + ps.name
7714                    + " is missing signatures.  Collecting certs again to recover them.");
7715        } else {
7716            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7717        }
7718
7719        try {
7720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7721            PackageParser.collectCertificates(pkg, policyFlags);
7722        } catch (PackageParserException e) {
7723            throw PackageManagerException.from(e);
7724        } finally {
7725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7726        }
7727    }
7728
7729    /**
7730     *  Traces a package scan.
7731     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7732     */
7733    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7734            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7735        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7736        try {
7737            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7738        } finally {
7739            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7740        }
7741    }
7742
7743    /**
7744     *  Scans a package and returns the newly parsed package.
7745     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7746     */
7747    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7748            long currentTime, UserHandle user) throws PackageManagerException {
7749        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7750        PackageParser pp = new PackageParser();
7751        pp.setSeparateProcesses(mSeparateProcesses);
7752        pp.setOnlyCoreApps(mOnlyCore);
7753        pp.setDisplayMetrics(mMetrics);
7754        pp.setCallback(mPackageParserCallback);
7755
7756        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7757            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7758        }
7759
7760        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7761        final PackageParser.Package pkg;
7762        try {
7763            pkg = pp.parsePackage(scanFile, parseFlags);
7764        } catch (PackageParserException e) {
7765            throw PackageManagerException.from(e);
7766        } finally {
7767            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7768        }
7769
7770        // Static shared libraries have synthetic package names
7771        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7772            renameStaticSharedLibraryPackage(pkg);
7773        }
7774
7775        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7776    }
7777
7778    /**
7779     *  Scans a package and returns the newly parsed package.
7780     *  @throws PackageManagerException on a parse error.
7781     */
7782    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7783            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7784            throws PackageManagerException {
7785        // If the package has children and this is the first dive in the function
7786        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7787        // packages (parent and children) would be successfully scanned before the
7788        // actual scan since scanning mutates internal state and we want to atomically
7789        // install the package and its children.
7790        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7791            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7792                scanFlags |= SCAN_CHECK_ONLY;
7793            }
7794        } else {
7795            scanFlags &= ~SCAN_CHECK_ONLY;
7796        }
7797
7798        // Scan the parent
7799        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7800                scanFlags, currentTime, user);
7801
7802        // Scan the children
7803        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7804        for (int i = 0; i < childCount; i++) {
7805            PackageParser.Package childPackage = pkg.childPackages.get(i);
7806            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7807                    currentTime, user);
7808        }
7809
7810
7811        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7812            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7813        }
7814
7815        return scannedPkg;
7816    }
7817
7818    /**
7819     *  Scans a package and returns the newly parsed package.
7820     *  @throws PackageManagerException on a parse error.
7821     */
7822    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7823            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7824            throws PackageManagerException {
7825        PackageSetting ps = null;
7826        PackageSetting updatedPkg;
7827        // reader
7828        synchronized (mPackages) {
7829            // Look to see if we already know about this package.
7830            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7831            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7832                // This package has been renamed to its original name.  Let's
7833                // use that.
7834                ps = mSettings.getPackageLPr(oldName);
7835            }
7836            // If there was no original package, see one for the real package name.
7837            if (ps == null) {
7838                ps = mSettings.getPackageLPr(pkg.packageName);
7839            }
7840            // Check to see if this package could be hiding/updating a system
7841            // package.  Must look for it either under the original or real
7842            // package name depending on our state.
7843            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7844            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7845
7846            // If this is a package we don't know about on the system partition, we
7847            // may need to remove disabled child packages on the system partition
7848            // or may need to not add child packages if the parent apk is updated
7849            // on the data partition and no longer defines this child package.
7850            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7851                // If this is a parent package for an updated system app and this system
7852                // app got an OTA update which no longer defines some of the child packages
7853                // we have to prune them from the disabled system packages.
7854                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7855                if (disabledPs != null) {
7856                    final int scannedChildCount = (pkg.childPackages != null)
7857                            ? pkg.childPackages.size() : 0;
7858                    final int disabledChildCount = disabledPs.childPackageNames != null
7859                            ? disabledPs.childPackageNames.size() : 0;
7860                    for (int i = 0; i < disabledChildCount; i++) {
7861                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7862                        boolean disabledPackageAvailable = false;
7863                        for (int j = 0; j < scannedChildCount; j++) {
7864                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7865                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7866                                disabledPackageAvailable = true;
7867                                break;
7868                            }
7869                         }
7870                         if (!disabledPackageAvailable) {
7871                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7872                         }
7873                    }
7874                }
7875            }
7876        }
7877
7878        boolean updatedPkgBetter = false;
7879        // First check if this is a system package that may involve an update
7880        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7881            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7882            // it needs to drop FLAG_PRIVILEGED.
7883            if (locationIsPrivileged(scanFile)) {
7884                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7885            } else {
7886                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7887            }
7888
7889            if (ps != null && !ps.codePath.equals(scanFile)) {
7890                // The path has changed from what was last scanned...  check the
7891                // version of the new path against what we have stored to determine
7892                // what to do.
7893                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7894                if (pkg.mVersionCode <= ps.versionCode) {
7895                    // The system package has been updated and the code path does not match
7896                    // Ignore entry. Skip it.
7897                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7898                            + " ignored: updated version " + ps.versionCode
7899                            + " better than this " + pkg.mVersionCode);
7900                    if (!updatedPkg.codePath.equals(scanFile)) {
7901                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7902                                + ps.name + " changing from " + updatedPkg.codePathString
7903                                + " to " + scanFile);
7904                        updatedPkg.codePath = scanFile;
7905                        updatedPkg.codePathString = scanFile.toString();
7906                        updatedPkg.resourcePath = scanFile;
7907                        updatedPkg.resourcePathString = scanFile.toString();
7908                    }
7909                    updatedPkg.pkg = pkg;
7910                    updatedPkg.versionCode = pkg.mVersionCode;
7911
7912                    // Update the disabled system child packages to point to the package too.
7913                    final int childCount = updatedPkg.childPackageNames != null
7914                            ? updatedPkg.childPackageNames.size() : 0;
7915                    for (int i = 0; i < childCount; i++) {
7916                        String childPackageName = updatedPkg.childPackageNames.get(i);
7917                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7918                                childPackageName);
7919                        if (updatedChildPkg != null) {
7920                            updatedChildPkg.pkg = pkg;
7921                            updatedChildPkg.versionCode = pkg.mVersionCode;
7922                        }
7923                    }
7924
7925                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7926                            + scanFile + " ignored: updated version " + ps.versionCode
7927                            + " better than this " + pkg.mVersionCode);
7928                } else {
7929                    // The current app on the system partition is better than
7930                    // what we have updated to on the data partition; switch
7931                    // back to the system partition version.
7932                    // At this point, its safely assumed that package installation for
7933                    // apps in system partition will go through. If not there won't be a working
7934                    // version of the app
7935                    // writer
7936                    synchronized (mPackages) {
7937                        // Just remove the loaded entries from package lists.
7938                        mPackages.remove(ps.name);
7939                    }
7940
7941                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7942                            + " reverting from " + ps.codePathString
7943                            + ": new version " + pkg.mVersionCode
7944                            + " better than installed " + ps.versionCode);
7945
7946                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7947                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7948                    synchronized (mInstallLock) {
7949                        args.cleanUpResourcesLI();
7950                    }
7951                    synchronized (mPackages) {
7952                        mSettings.enableSystemPackageLPw(ps.name);
7953                    }
7954                    updatedPkgBetter = true;
7955                }
7956            }
7957        }
7958
7959        if (updatedPkg != null) {
7960            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7961            // initially
7962            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7963
7964            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7965            // flag set initially
7966            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7967                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7968            }
7969        }
7970
7971        // Verify certificates against what was last scanned
7972        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7973
7974        /*
7975         * A new system app appeared, but we already had a non-system one of the
7976         * same name installed earlier.
7977         */
7978        boolean shouldHideSystemApp = false;
7979        if (updatedPkg == null && ps != null
7980                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7981            /*
7982             * Check to make sure the signatures match first. If they don't,
7983             * wipe the installed application and its data.
7984             */
7985            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7986                    != PackageManager.SIGNATURE_MATCH) {
7987                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7988                        + " signatures don't match existing userdata copy; removing");
7989                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7990                        "scanPackageInternalLI")) {
7991                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7992                }
7993                ps = null;
7994            } else {
7995                /*
7996                 * If the newly-added system app is an older version than the
7997                 * already installed version, hide it. It will be scanned later
7998                 * and re-added like an update.
7999                 */
8000                if (pkg.mVersionCode <= ps.versionCode) {
8001                    shouldHideSystemApp = true;
8002                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8003                            + " but new version " + pkg.mVersionCode + " better than installed "
8004                            + ps.versionCode + "; hiding system");
8005                } else {
8006                    /*
8007                     * The newly found system app is a newer version that the
8008                     * one previously installed. Simply remove the
8009                     * already-installed application and replace it with our own
8010                     * while keeping the application data.
8011                     */
8012                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8013                            + " reverting from " + ps.codePathString + ": new version "
8014                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8015                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8016                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8017                    synchronized (mInstallLock) {
8018                        args.cleanUpResourcesLI();
8019                    }
8020                }
8021            }
8022        }
8023
8024        // The apk is forward locked (not public) if its code and resources
8025        // are kept in different files. (except for app in either system or
8026        // vendor path).
8027        // TODO grab this value from PackageSettings
8028        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8029            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8030                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8031            }
8032        }
8033
8034        // TODO: extend to support forward-locked splits
8035        String resourcePath = null;
8036        String baseResourcePath = null;
8037        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8038            if (ps != null && ps.resourcePathString != null) {
8039                resourcePath = ps.resourcePathString;
8040                baseResourcePath = ps.resourcePathString;
8041            } else {
8042                // Should not happen at all. Just log an error.
8043                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8044            }
8045        } else {
8046            resourcePath = pkg.codePath;
8047            baseResourcePath = pkg.baseCodePath;
8048        }
8049
8050        // Set application objects path explicitly.
8051        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8052        pkg.setApplicationInfoCodePath(pkg.codePath);
8053        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8054        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8055        pkg.setApplicationInfoResourcePath(resourcePath);
8056        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8057        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8058
8059        final int userId = ((user == null) ? 0 : user.getIdentifier());
8060        if (ps != null && ps.getInstantApp(userId)) {
8061            scanFlags |= SCAN_AS_INSTANT_APP;
8062        }
8063
8064        // Note that we invoke the following method only if we are about to unpack an application
8065        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8066                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8067
8068        /*
8069         * If the system app should be overridden by a previously installed
8070         * data, hide the system app now and let the /data/app scan pick it up
8071         * again.
8072         */
8073        if (shouldHideSystemApp) {
8074            synchronized (mPackages) {
8075                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8076            }
8077        }
8078
8079        return scannedPkg;
8080    }
8081
8082    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8083        // Derive the new package synthetic package name
8084        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8085                + pkg.staticSharedLibVersion);
8086    }
8087
8088    private static String fixProcessName(String defProcessName,
8089            String processName) {
8090        if (processName == null) {
8091            return defProcessName;
8092        }
8093        return processName;
8094    }
8095
8096    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8097            throws PackageManagerException {
8098        if (pkgSetting.signatures.mSignatures != null) {
8099            // Already existing package. Make sure signatures match
8100            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8101                    == PackageManager.SIGNATURE_MATCH;
8102            if (!match) {
8103                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8104                        == PackageManager.SIGNATURE_MATCH;
8105            }
8106            if (!match) {
8107                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8108                        == PackageManager.SIGNATURE_MATCH;
8109            }
8110            if (!match) {
8111                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8112                        + pkg.packageName + " signatures do not match the "
8113                        + "previously installed version; ignoring!");
8114            }
8115        }
8116
8117        // Check for shared user signatures
8118        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8119            // Already existing package. Make sure signatures match
8120            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8121                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8122            if (!match) {
8123                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8124                        == PackageManager.SIGNATURE_MATCH;
8125            }
8126            if (!match) {
8127                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8128                        == PackageManager.SIGNATURE_MATCH;
8129            }
8130            if (!match) {
8131                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8132                        "Package " + pkg.packageName
8133                        + " has no signatures that match those in shared user "
8134                        + pkgSetting.sharedUser.name + "; ignoring!");
8135            }
8136        }
8137    }
8138
8139    /**
8140     * Enforces that only the system UID or root's UID can call a method exposed
8141     * via Binder.
8142     *
8143     * @param message used as message if SecurityException is thrown
8144     * @throws SecurityException if the caller is not system or root
8145     */
8146    private static final void enforceSystemOrRoot(String message) {
8147        final int uid = Binder.getCallingUid();
8148        if (uid != Process.SYSTEM_UID && uid != 0) {
8149            throw new SecurityException(message);
8150        }
8151    }
8152
8153    @Override
8154    public void performFstrimIfNeeded() {
8155        enforceSystemOrRoot("Only the system can request fstrim");
8156
8157        // Before everything else, see whether we need to fstrim.
8158        try {
8159            IStorageManager sm = PackageHelper.getStorageManager();
8160            if (sm != null) {
8161                boolean doTrim = false;
8162                final long interval = android.provider.Settings.Global.getLong(
8163                        mContext.getContentResolver(),
8164                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8165                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8166                if (interval > 0) {
8167                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8168                    if (timeSinceLast > interval) {
8169                        doTrim = true;
8170                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8171                                + "; running immediately");
8172                    }
8173                }
8174                if (doTrim) {
8175                    final boolean dexOptDialogShown;
8176                    synchronized (mPackages) {
8177                        dexOptDialogShown = mDexOptDialogShown;
8178                    }
8179                    if (!isFirstBoot() && dexOptDialogShown) {
8180                        try {
8181                            ActivityManager.getService().showBootMessage(
8182                                    mContext.getResources().getString(
8183                                            R.string.android_upgrading_fstrim), true);
8184                        } catch (RemoteException e) {
8185                        }
8186                    }
8187                    sm.runMaintenance();
8188                }
8189            } else {
8190                Slog.e(TAG, "storageManager service unavailable!");
8191            }
8192        } catch (RemoteException e) {
8193            // Can't happen; StorageManagerService is local
8194        }
8195    }
8196
8197    @Override
8198    public void updatePackagesIfNeeded() {
8199        enforceSystemOrRoot("Only the system can request package update");
8200
8201        // We need to re-extract after an OTA.
8202        boolean causeUpgrade = isUpgrade();
8203
8204        // First boot or factory reset.
8205        // Note: we also handle devices that are upgrading to N right now as if it is their
8206        //       first boot, as they do not have profile data.
8207        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8208
8209        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8210        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8211
8212        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8213            return;
8214        }
8215
8216        List<PackageParser.Package> pkgs;
8217        synchronized (mPackages) {
8218            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8219        }
8220
8221        final long startTime = System.nanoTime();
8222        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8223                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8224
8225        final int elapsedTimeSeconds =
8226                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8227
8228        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8229        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8230        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8231        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8232        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8233    }
8234
8235    /**
8236     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8237     * containing statistics about the invocation. The array consists of three elements,
8238     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8239     * and {@code numberOfPackagesFailed}.
8240     */
8241    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8242            String compilerFilter) {
8243
8244        int numberOfPackagesVisited = 0;
8245        int numberOfPackagesOptimized = 0;
8246        int numberOfPackagesSkipped = 0;
8247        int numberOfPackagesFailed = 0;
8248        final int numberOfPackagesToDexopt = pkgs.size();
8249
8250        for (PackageParser.Package pkg : pkgs) {
8251            numberOfPackagesVisited++;
8252
8253            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8254                if (DEBUG_DEXOPT) {
8255                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8256                }
8257                numberOfPackagesSkipped++;
8258                continue;
8259            }
8260
8261            if (DEBUG_DEXOPT) {
8262                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8263                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8264            }
8265
8266            if (showDialog) {
8267                try {
8268                    ActivityManager.getService().showBootMessage(
8269                            mContext.getResources().getString(R.string.android_upgrading_apk,
8270                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8271                } catch (RemoteException e) {
8272                }
8273                synchronized (mPackages) {
8274                    mDexOptDialogShown = true;
8275                }
8276            }
8277
8278            // If the OTA updates a system app which was previously preopted to a non-preopted state
8279            // the app might end up being verified at runtime. That's because by default the apps
8280            // are verify-profile but for preopted apps there's no profile.
8281            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8282            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8283            // filter (by default interpret-only).
8284            // Note that at this stage unused apps are already filtered.
8285            if (isSystemApp(pkg) &&
8286                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8287                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8288                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8289            }
8290
8291            // checkProfiles is false to avoid merging profiles during boot which
8292            // might interfere with background compilation (b/28612421).
8293            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8294            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8295            // trade-off worth doing to save boot time work.
8296            int dexOptStatus = performDexOptTraced(pkg.packageName,
8297                    false /* checkProfiles */,
8298                    compilerFilter,
8299                    false /* force */);
8300            switch (dexOptStatus) {
8301                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8302                    numberOfPackagesOptimized++;
8303                    break;
8304                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8305                    numberOfPackagesSkipped++;
8306                    break;
8307                case PackageDexOptimizer.DEX_OPT_FAILED:
8308                    numberOfPackagesFailed++;
8309                    break;
8310                default:
8311                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8312                    break;
8313            }
8314        }
8315
8316        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8317                numberOfPackagesFailed };
8318    }
8319
8320    @Override
8321    public void notifyPackageUse(String packageName, int reason) {
8322        synchronized (mPackages) {
8323            PackageParser.Package p = mPackages.get(packageName);
8324            if (p == null) {
8325                return;
8326            }
8327            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8328        }
8329    }
8330
8331    @Override
8332    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8333        int userId = UserHandle.getCallingUserId();
8334        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8335        if (ai == null) {
8336            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8337                + loadingPackageName + ", user=" + userId);
8338            return;
8339        }
8340        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8341    }
8342
8343    // TODO: this is not used nor needed. Delete it.
8344    @Override
8345    public boolean performDexOptIfNeeded(String packageName) {
8346        int dexOptStatus = performDexOptTraced(packageName,
8347                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8348        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8349    }
8350
8351    @Override
8352    public boolean performDexOpt(String packageName,
8353            boolean checkProfiles, int compileReason, boolean force) {
8354        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8355                getCompilerFilterForReason(compileReason), force);
8356        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8357    }
8358
8359    @Override
8360    public boolean performDexOptMode(String packageName,
8361            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8362        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8363                targetCompilerFilter, force);
8364        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8365    }
8366
8367    private int performDexOptTraced(String packageName,
8368                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8369        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8370        try {
8371            return performDexOptInternal(packageName, checkProfiles,
8372                    targetCompilerFilter, force);
8373        } finally {
8374            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8375        }
8376    }
8377
8378    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8379    // if the package can now be considered up to date for the given filter.
8380    private int performDexOptInternal(String packageName,
8381                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8382        PackageParser.Package p;
8383        synchronized (mPackages) {
8384            p = mPackages.get(packageName);
8385            if (p == null) {
8386                // Package could not be found. Report failure.
8387                return PackageDexOptimizer.DEX_OPT_FAILED;
8388            }
8389            mPackageUsage.maybeWriteAsync(mPackages);
8390            mCompilerStats.maybeWriteAsync();
8391        }
8392        long callingId = Binder.clearCallingIdentity();
8393        try {
8394            synchronized (mInstallLock) {
8395                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8396                        targetCompilerFilter, force);
8397            }
8398        } finally {
8399            Binder.restoreCallingIdentity(callingId);
8400        }
8401    }
8402
8403    public ArraySet<String> getOptimizablePackages() {
8404        ArraySet<String> pkgs = new ArraySet<String>();
8405        synchronized (mPackages) {
8406            for (PackageParser.Package p : mPackages.values()) {
8407                if (PackageDexOptimizer.canOptimizePackage(p)) {
8408                    pkgs.add(p.packageName);
8409                }
8410            }
8411        }
8412        return pkgs;
8413    }
8414
8415    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8416            boolean checkProfiles, String targetCompilerFilter,
8417            boolean force) {
8418        // Select the dex optimizer based on the force parameter.
8419        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8420        //       allocate an object here.
8421        PackageDexOptimizer pdo = force
8422                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8423                : mPackageDexOptimizer;
8424
8425        // Dexopt all dependencies first. Note: we ignore the return value and march on
8426        // on errors.
8427        // Note that we are going to call performDexOpt on those libraries as many times as
8428        // they are referenced in packages. When we do a batch of performDexOpt (for example
8429        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8430        // and the first package that uses the library will dexopt it. The
8431        // others will see that the compiled code for the library is up to date.
8432        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8433        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8434        if (!deps.isEmpty()) {
8435            for (PackageParser.Package depPackage : deps) {
8436                // TODO: Analyze and investigate if we (should) profile libraries.
8437                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8438                        false /* checkProfiles */,
8439                        targetCompilerFilter,
8440                        getOrCreateCompilerPackageStats(depPackage),
8441                        true /* isUsedByOtherApps */);
8442            }
8443        }
8444        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8445                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8446                mDexManager.isUsedByOtherApps(p.packageName));
8447    }
8448
8449    // Performs dexopt on the used secondary dex files belonging to the given package.
8450    // Returns true if all dex files were process successfully (which could mean either dexopt or
8451    // skip). Returns false if any of the files caused errors.
8452    @Override
8453    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8454            boolean force) {
8455        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8456    }
8457
8458    public boolean performDexOptSecondary(String packageName, int compileReason,
8459            boolean force) {
8460        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8461    }
8462
8463    /**
8464     * Reconcile the information we have about the secondary dex files belonging to
8465     * {@code packagName} and the actual dex files. For all dex files that were
8466     * deleted, update the internal records and delete the generated oat files.
8467     */
8468    @Override
8469    public void reconcileSecondaryDexFiles(String packageName) {
8470        mDexManager.reconcileSecondaryDexFiles(packageName);
8471    }
8472
8473    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8474    // a reference there.
8475    /*package*/ DexManager getDexManager() {
8476        return mDexManager;
8477    }
8478
8479    /**
8480     * Execute the background dexopt job immediately.
8481     */
8482    @Override
8483    public boolean runBackgroundDexoptJob() {
8484        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8485    }
8486
8487    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8488        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8489                || p.usesStaticLibraries != null) {
8490            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8491            Set<String> collectedNames = new HashSet<>();
8492            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8493
8494            retValue.remove(p);
8495
8496            return retValue;
8497        } else {
8498            return Collections.emptyList();
8499        }
8500    }
8501
8502    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8503            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8504        if (!collectedNames.contains(p.packageName)) {
8505            collectedNames.add(p.packageName);
8506            collected.add(p);
8507
8508            if (p.usesLibraries != null) {
8509                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8510                        null, collected, collectedNames);
8511            }
8512            if (p.usesOptionalLibraries != null) {
8513                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8514                        null, collected, collectedNames);
8515            }
8516            if (p.usesStaticLibraries != null) {
8517                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8518                        p.usesStaticLibrariesVersions, collected, collectedNames);
8519            }
8520        }
8521    }
8522
8523    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8524            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8525        final int libNameCount = libs.size();
8526        for (int i = 0; i < libNameCount; i++) {
8527            String libName = libs.get(i);
8528            int version = (versions != null && versions.length == libNameCount)
8529                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8530            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8531            if (libPkg != null) {
8532                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8533            }
8534        }
8535    }
8536
8537    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8538        synchronized (mPackages) {
8539            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8540            if (libEntry != null) {
8541                return mPackages.get(libEntry.apk);
8542            }
8543            return null;
8544        }
8545    }
8546
8547    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8548        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8549        if (versionedLib == null) {
8550            return null;
8551        }
8552        return versionedLib.get(version);
8553    }
8554
8555    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8556        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8557                pkg.staticSharedLibName);
8558        if (versionedLib == null) {
8559            return null;
8560        }
8561        int previousLibVersion = -1;
8562        final int versionCount = versionedLib.size();
8563        for (int i = 0; i < versionCount; i++) {
8564            final int libVersion = versionedLib.keyAt(i);
8565            if (libVersion < pkg.staticSharedLibVersion) {
8566                previousLibVersion = Math.max(previousLibVersion, libVersion);
8567            }
8568        }
8569        if (previousLibVersion >= 0) {
8570            return versionedLib.get(previousLibVersion);
8571        }
8572        return null;
8573    }
8574
8575    public void shutdown() {
8576        mPackageUsage.writeNow(mPackages);
8577        mCompilerStats.writeNow();
8578    }
8579
8580    @Override
8581    public void dumpProfiles(String packageName) {
8582        PackageParser.Package pkg;
8583        synchronized (mPackages) {
8584            pkg = mPackages.get(packageName);
8585            if (pkg == null) {
8586                throw new IllegalArgumentException("Unknown package: " + packageName);
8587            }
8588        }
8589        /* Only the shell, root, or the app user should be able to dump profiles. */
8590        int callingUid = Binder.getCallingUid();
8591        if (callingUid != Process.SHELL_UID &&
8592            callingUid != Process.ROOT_UID &&
8593            callingUid != pkg.applicationInfo.uid) {
8594            throw new SecurityException("dumpProfiles");
8595        }
8596
8597        synchronized (mInstallLock) {
8598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8599            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8600            try {
8601                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8602                String codePaths = TextUtils.join(";", allCodePaths);
8603                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8604            } catch (InstallerException e) {
8605                Slog.w(TAG, "Failed to dump profiles", e);
8606            }
8607            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8608        }
8609    }
8610
8611    @Override
8612    public void forceDexOpt(String packageName) {
8613        enforceSystemOrRoot("forceDexOpt");
8614
8615        PackageParser.Package pkg;
8616        synchronized (mPackages) {
8617            pkg = mPackages.get(packageName);
8618            if (pkg == null) {
8619                throw new IllegalArgumentException("Unknown package: " + packageName);
8620            }
8621        }
8622
8623        synchronized (mInstallLock) {
8624            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8625
8626            // Whoever is calling forceDexOpt wants a fully compiled package.
8627            // Don't use profiles since that may cause compilation to be skipped.
8628            final int res = performDexOptInternalWithDependenciesLI(pkg,
8629                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8630                    true /* force */);
8631
8632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8633            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8634                throw new IllegalStateException("Failed to dexopt: " + res);
8635            }
8636        }
8637    }
8638
8639    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8640        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8641            Slog.w(TAG, "Unable to update from " + oldPkg.name
8642                    + " to " + newPkg.packageName
8643                    + ": old package not in system partition");
8644            return false;
8645        } else if (mPackages.get(oldPkg.name) != null) {
8646            Slog.w(TAG, "Unable to update from " + oldPkg.name
8647                    + " to " + newPkg.packageName
8648                    + ": old package still exists");
8649            return false;
8650        }
8651        return true;
8652    }
8653
8654    void removeCodePathLI(File codePath) {
8655        if (codePath.isDirectory()) {
8656            try {
8657                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8658            } catch (InstallerException e) {
8659                Slog.w(TAG, "Failed to remove code path", e);
8660            }
8661        } else {
8662            codePath.delete();
8663        }
8664    }
8665
8666    private int[] resolveUserIds(int userId) {
8667        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8668    }
8669
8670    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8671        if (pkg == null) {
8672            Slog.wtf(TAG, "Package was null!", new Throwable());
8673            return;
8674        }
8675        clearAppDataLeafLIF(pkg, userId, flags);
8676        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8677        for (int i = 0; i < childCount; i++) {
8678            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8679        }
8680    }
8681
8682    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8683        final PackageSetting ps;
8684        synchronized (mPackages) {
8685            ps = mSettings.mPackages.get(pkg.packageName);
8686        }
8687        for (int realUserId : resolveUserIds(userId)) {
8688            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8689            try {
8690                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8691                        ceDataInode);
8692            } catch (InstallerException e) {
8693                Slog.w(TAG, String.valueOf(e));
8694            }
8695        }
8696    }
8697
8698    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8699        if (pkg == null) {
8700            Slog.wtf(TAG, "Package was null!", new Throwable());
8701            return;
8702        }
8703        destroyAppDataLeafLIF(pkg, userId, flags);
8704        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8705        for (int i = 0; i < childCount; i++) {
8706            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8707        }
8708    }
8709
8710    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8711        final PackageSetting ps;
8712        synchronized (mPackages) {
8713            ps = mSettings.mPackages.get(pkg.packageName);
8714        }
8715        for (int realUserId : resolveUserIds(userId)) {
8716            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8717            try {
8718                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8719                        ceDataInode);
8720            } catch (InstallerException e) {
8721                Slog.w(TAG, String.valueOf(e));
8722            }
8723            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8724        }
8725    }
8726
8727    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8728        if (pkg == null) {
8729            Slog.wtf(TAG, "Package was null!", new Throwable());
8730            return;
8731        }
8732        destroyAppProfilesLeafLIF(pkg);
8733        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8734        for (int i = 0; i < childCount; i++) {
8735            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8736        }
8737    }
8738
8739    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8740        try {
8741            mInstaller.destroyAppProfiles(pkg.packageName);
8742        } catch (InstallerException e) {
8743            Slog.w(TAG, String.valueOf(e));
8744        }
8745    }
8746
8747    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8748        if (pkg == null) {
8749            Slog.wtf(TAG, "Package was null!", new Throwable());
8750            return;
8751        }
8752        clearAppProfilesLeafLIF(pkg);
8753        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8754        for (int i = 0; i < childCount; i++) {
8755            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8756        }
8757    }
8758
8759    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8760        try {
8761            mInstaller.clearAppProfiles(pkg.packageName);
8762        } catch (InstallerException e) {
8763            Slog.w(TAG, String.valueOf(e));
8764        }
8765    }
8766
8767    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8768            long lastUpdateTime) {
8769        // Set parent install/update time
8770        PackageSetting ps = (PackageSetting) pkg.mExtras;
8771        if (ps != null) {
8772            ps.firstInstallTime = firstInstallTime;
8773            ps.lastUpdateTime = lastUpdateTime;
8774        }
8775        // Set children install/update time
8776        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8777        for (int i = 0; i < childCount; i++) {
8778            PackageParser.Package childPkg = pkg.childPackages.get(i);
8779            ps = (PackageSetting) childPkg.mExtras;
8780            if (ps != null) {
8781                ps.firstInstallTime = firstInstallTime;
8782                ps.lastUpdateTime = lastUpdateTime;
8783            }
8784        }
8785    }
8786
8787    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8788            PackageParser.Package changingLib) {
8789        if (file.path != null) {
8790            usesLibraryFiles.add(file.path);
8791            return;
8792        }
8793        PackageParser.Package p = mPackages.get(file.apk);
8794        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8795            // If we are doing this while in the middle of updating a library apk,
8796            // then we need to make sure to use that new apk for determining the
8797            // dependencies here.  (We haven't yet finished committing the new apk
8798            // to the package manager state.)
8799            if (p == null || p.packageName.equals(changingLib.packageName)) {
8800                p = changingLib;
8801            }
8802        }
8803        if (p != null) {
8804            usesLibraryFiles.addAll(p.getAllCodePaths());
8805        }
8806    }
8807
8808    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8809            PackageParser.Package changingLib) throws PackageManagerException {
8810        if (pkg == null) {
8811            return;
8812        }
8813        ArraySet<String> usesLibraryFiles = null;
8814        if (pkg.usesLibraries != null) {
8815            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8816                    null, null, pkg.packageName, changingLib, true, null);
8817        }
8818        if (pkg.usesStaticLibraries != null) {
8819            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8820                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8821                    pkg.packageName, changingLib, true, usesLibraryFiles);
8822        }
8823        if (pkg.usesOptionalLibraries != null) {
8824            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8825                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8826        }
8827        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8828            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8829        } else {
8830            pkg.usesLibraryFiles = null;
8831        }
8832    }
8833
8834    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8835            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8836            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8837            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8838            throws PackageManagerException {
8839        final int libCount = requestedLibraries.size();
8840        for (int i = 0; i < libCount; i++) {
8841            final String libName = requestedLibraries.get(i);
8842            final int libVersion = requiredVersions != null ? requiredVersions[i]
8843                    : SharedLibraryInfo.VERSION_UNDEFINED;
8844            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8845            if (libEntry == null) {
8846                if (required) {
8847                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8848                            "Package " + packageName + " requires unavailable shared library "
8849                                    + libName + "; failing!");
8850                } else {
8851                    Slog.w(TAG, "Package " + packageName
8852                            + " desires unavailable shared library "
8853                            + libName + "; ignoring!");
8854                }
8855            } else {
8856                if (requiredVersions != null && requiredCertDigests != null) {
8857                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8858                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8859                            "Package " + packageName + " requires unavailable static shared"
8860                                    + " library " + libName + " version "
8861                                    + libEntry.info.getVersion() + "; failing!");
8862                    }
8863
8864                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8865                    if (libPkg == null) {
8866                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8867                                "Package " + packageName + " requires unavailable static shared"
8868                                        + " library; failing!");
8869                    }
8870
8871                    String expectedCertDigest = requiredCertDigests[i];
8872                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8873                                libPkg.mSignatures[0]);
8874                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8875                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8876                                "Package " + packageName + " requires differently signed" +
8877                                        " static shared library; failing!");
8878                    }
8879                }
8880
8881                if (outUsedLibraries == null) {
8882                    outUsedLibraries = new ArraySet<>();
8883                }
8884                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8885            }
8886        }
8887        return outUsedLibraries;
8888    }
8889
8890    private static boolean hasString(List<String> list, List<String> which) {
8891        if (list == null) {
8892            return false;
8893        }
8894        for (int i=list.size()-1; i>=0; i--) {
8895            for (int j=which.size()-1; j>=0; j--) {
8896                if (which.get(j).equals(list.get(i))) {
8897                    return true;
8898                }
8899            }
8900        }
8901        return false;
8902    }
8903
8904    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8905            PackageParser.Package changingPkg) {
8906        ArrayList<PackageParser.Package> res = null;
8907        for (PackageParser.Package pkg : mPackages.values()) {
8908            if (changingPkg != null
8909                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8910                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8911                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8912                            changingPkg.staticSharedLibName)) {
8913                return null;
8914            }
8915            if (res == null) {
8916                res = new ArrayList<>();
8917            }
8918            res.add(pkg);
8919            try {
8920                updateSharedLibrariesLPr(pkg, changingPkg);
8921            } catch (PackageManagerException e) {
8922                // If a system app update or an app and a required lib missing we
8923                // delete the package and for updated system apps keep the data as
8924                // it is better for the user to reinstall than to be in an limbo
8925                // state. Also libs disappearing under an app should never happen
8926                // - just in case.
8927                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8928                    final int flags = pkg.isUpdatedSystemApp()
8929                            ? PackageManager.DELETE_KEEP_DATA : 0;
8930                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8931                            flags , null, true, null);
8932                }
8933                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8934            }
8935        }
8936        return res;
8937    }
8938
8939    /**
8940     * Derive the value of the {@code cpuAbiOverride} based on the provided
8941     * value and an optional stored value from the package settings.
8942     */
8943    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8944        String cpuAbiOverride = null;
8945
8946        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8947            cpuAbiOverride = null;
8948        } else if (abiOverride != null) {
8949            cpuAbiOverride = abiOverride;
8950        } else if (settings != null) {
8951            cpuAbiOverride = settings.cpuAbiOverrideString;
8952        }
8953
8954        return cpuAbiOverride;
8955    }
8956
8957    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8958            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8959                    throws PackageManagerException {
8960        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8961        // If the package has children and this is the first dive in the function
8962        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8963        // whether all packages (parent and children) would be successfully scanned
8964        // before the actual scan since scanning mutates internal state and we want
8965        // to atomically install the package and its children.
8966        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8967            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8968                scanFlags |= SCAN_CHECK_ONLY;
8969            }
8970        } else {
8971            scanFlags &= ~SCAN_CHECK_ONLY;
8972        }
8973
8974        final PackageParser.Package scannedPkg;
8975        try {
8976            // Scan the parent
8977            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8978            // Scan the children
8979            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8980            for (int i = 0; i < childCount; i++) {
8981                PackageParser.Package childPkg = pkg.childPackages.get(i);
8982                scanPackageLI(childPkg, policyFlags,
8983                        scanFlags, currentTime, user);
8984            }
8985        } finally {
8986            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8987        }
8988
8989        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8990            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8991        }
8992
8993        return scannedPkg;
8994    }
8995
8996    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8997            int scanFlags, long currentTime, @Nullable UserHandle user)
8998                    throws PackageManagerException {
8999        boolean success = false;
9000        try {
9001            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9002                    currentTime, user);
9003            success = true;
9004            return res;
9005        } finally {
9006            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9007                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9008                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9009                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9010                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9011            }
9012        }
9013    }
9014
9015    /**
9016     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9017     */
9018    private static boolean apkHasCode(String fileName) {
9019        StrictJarFile jarFile = null;
9020        try {
9021            jarFile = new StrictJarFile(fileName,
9022                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9023            return jarFile.findEntry("classes.dex") != null;
9024        } catch (IOException ignore) {
9025        } finally {
9026            try {
9027                if (jarFile != null) {
9028                    jarFile.close();
9029                }
9030            } catch (IOException ignore) {}
9031        }
9032        return false;
9033    }
9034
9035    /**
9036     * Enforces code policy for the package. This ensures that if an APK has
9037     * declared hasCode="true" in its manifest that the APK actually contains
9038     * code.
9039     *
9040     * @throws PackageManagerException If bytecode could not be found when it should exist
9041     */
9042    private static void assertCodePolicy(PackageParser.Package pkg)
9043            throws PackageManagerException {
9044        final boolean shouldHaveCode =
9045                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9046        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9047            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9048                    "Package " + pkg.baseCodePath + " code is missing");
9049        }
9050
9051        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9052            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9053                final boolean splitShouldHaveCode =
9054                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9055                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9056                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9057                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9058                }
9059            }
9060        }
9061    }
9062
9063    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9064            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9065                    throws PackageManagerException {
9066        if (DEBUG_PACKAGE_SCANNING) {
9067            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9068                Log.d(TAG, "Scanning package " + pkg.packageName);
9069        }
9070
9071        applyPolicy(pkg, policyFlags);
9072
9073        assertPackageIsValid(pkg, policyFlags, scanFlags);
9074
9075        // Initialize package source and resource directories
9076        final File scanFile = new File(pkg.codePath);
9077        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9078        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9079
9080        SharedUserSetting suid = null;
9081        PackageSetting pkgSetting = null;
9082
9083        // Getting the package setting may have a side-effect, so if we
9084        // are only checking if scan would succeed, stash a copy of the
9085        // old setting to restore at the end.
9086        PackageSetting nonMutatedPs = null;
9087
9088        // We keep references to the derived CPU Abis from settings in oder to reuse
9089        // them in the case where we're not upgrading or booting for the first time.
9090        String primaryCpuAbiFromSettings = null;
9091        String secondaryCpuAbiFromSettings = null;
9092
9093        // writer
9094        synchronized (mPackages) {
9095            if (pkg.mSharedUserId != null) {
9096                // SIDE EFFECTS; may potentially allocate a new shared user
9097                suid = mSettings.getSharedUserLPw(
9098                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9099                if (DEBUG_PACKAGE_SCANNING) {
9100                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9101                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9102                                + "): packages=" + suid.packages);
9103                }
9104            }
9105
9106            // Check if we are renaming from an original package name.
9107            PackageSetting origPackage = null;
9108            String realName = null;
9109            if (pkg.mOriginalPackages != null) {
9110                // This package may need to be renamed to a previously
9111                // installed name.  Let's check on that...
9112                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9113                if (pkg.mOriginalPackages.contains(renamed)) {
9114                    // This package had originally been installed as the
9115                    // original name, and we have already taken care of
9116                    // transitioning to the new one.  Just update the new
9117                    // one to continue using the old name.
9118                    realName = pkg.mRealPackage;
9119                    if (!pkg.packageName.equals(renamed)) {
9120                        // Callers into this function may have already taken
9121                        // care of renaming the package; only do it here if
9122                        // it is not already done.
9123                        pkg.setPackageName(renamed);
9124                    }
9125                } else {
9126                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9127                        if ((origPackage = mSettings.getPackageLPr(
9128                                pkg.mOriginalPackages.get(i))) != null) {
9129                            // We do have the package already installed under its
9130                            // original name...  should we use it?
9131                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9132                                // New package is not compatible with original.
9133                                origPackage = null;
9134                                continue;
9135                            } else if (origPackage.sharedUser != null) {
9136                                // Make sure uid is compatible between packages.
9137                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9138                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9139                                            + " to " + pkg.packageName + ": old uid "
9140                                            + origPackage.sharedUser.name
9141                                            + " differs from " + pkg.mSharedUserId);
9142                                    origPackage = null;
9143                                    continue;
9144                                }
9145                                // TODO: Add case when shared user id is added [b/28144775]
9146                            } else {
9147                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9148                                        + pkg.packageName + " to old name " + origPackage.name);
9149                            }
9150                            break;
9151                        }
9152                    }
9153                }
9154            }
9155
9156            if (mTransferedPackages.contains(pkg.packageName)) {
9157                Slog.w(TAG, "Package " + pkg.packageName
9158                        + " was transferred to another, but its .apk remains");
9159            }
9160
9161            // See comments in nonMutatedPs declaration
9162            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9163                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9164                if (foundPs != null) {
9165                    nonMutatedPs = new PackageSetting(foundPs);
9166                }
9167            }
9168
9169            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9170                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9171                if (foundPs != null) {
9172                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9173                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9174                }
9175            }
9176
9177            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9178            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9179                PackageManagerService.reportSettingsProblem(Log.WARN,
9180                        "Package " + pkg.packageName + " shared user changed from "
9181                                + (pkgSetting.sharedUser != null
9182                                        ? pkgSetting.sharedUser.name : "<nothing>")
9183                                + " to "
9184                                + (suid != null ? suid.name : "<nothing>")
9185                                + "; replacing with new");
9186                pkgSetting = null;
9187            }
9188            final PackageSetting oldPkgSetting =
9189                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9190            final PackageSetting disabledPkgSetting =
9191                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9192
9193            String[] usesStaticLibraries = null;
9194            if (pkg.usesStaticLibraries != null) {
9195                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9196                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9197            }
9198
9199            if (pkgSetting == null) {
9200                final String parentPackageName = (pkg.parentPackage != null)
9201                        ? pkg.parentPackage.packageName : null;
9202                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9203                // REMOVE SharedUserSetting from method; update in a separate call
9204                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9205                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9206                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9207                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9208                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9209                        true /*allowInstall*/, instantApp, parentPackageName,
9210                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9211                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9212                // SIDE EFFECTS; updates system state; move elsewhere
9213                if (origPackage != null) {
9214                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9215                }
9216                mSettings.addUserToSettingLPw(pkgSetting);
9217            } else {
9218                // REMOVE SharedUserSetting from method; update in a separate call.
9219                //
9220                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9221                // secondaryCpuAbi are not known at this point so we always update them
9222                // to null here, only to reset them at a later point.
9223                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9224                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9225                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9226                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9227                        UserManagerService.getInstance(), usesStaticLibraries,
9228                        pkg.usesStaticLibrariesVersions);
9229            }
9230            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9231            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9232
9233            // SIDE EFFECTS; modifies system state; move elsewhere
9234            if (pkgSetting.origPackage != null) {
9235                // If we are first transitioning from an original package,
9236                // fix up the new package's name now.  We need to do this after
9237                // looking up the package under its new name, so getPackageLP
9238                // can take care of fiddling things correctly.
9239                pkg.setPackageName(origPackage.name);
9240
9241                // File a report about this.
9242                String msg = "New package " + pkgSetting.realName
9243                        + " renamed to replace old package " + pkgSetting.name;
9244                reportSettingsProblem(Log.WARN, msg);
9245
9246                // Make a note of it.
9247                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9248                    mTransferedPackages.add(origPackage.name);
9249                }
9250
9251                // No longer need to retain this.
9252                pkgSetting.origPackage = null;
9253            }
9254
9255            // SIDE EFFECTS; modifies system state; move elsewhere
9256            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9257                // Make a note of it.
9258                mTransferedPackages.add(pkg.packageName);
9259            }
9260
9261            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9262                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9263            }
9264
9265            if ((scanFlags & SCAN_BOOTING) == 0
9266                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9267                // Check all shared libraries and map to their actual file path.
9268                // We only do this here for apps not on a system dir, because those
9269                // are the only ones that can fail an install due to this.  We
9270                // will take care of the system apps by updating all of their
9271                // library paths after the scan is done. Also during the initial
9272                // scan don't update any libs as we do this wholesale after all
9273                // apps are scanned to avoid dependency based scanning.
9274                updateSharedLibrariesLPr(pkg, null);
9275            }
9276
9277            if (mFoundPolicyFile) {
9278                SELinuxMMAC.assignSeInfoValue(pkg);
9279            }
9280            pkg.applicationInfo.uid = pkgSetting.appId;
9281            pkg.mExtras = pkgSetting;
9282
9283
9284            // Static shared libs have same package with different versions where
9285            // we internally use a synthetic package name to allow multiple versions
9286            // of the same package, therefore we need to compare signatures against
9287            // the package setting for the latest library version.
9288            PackageSetting signatureCheckPs = pkgSetting;
9289            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9290                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9291                if (libraryEntry != null) {
9292                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9293                }
9294            }
9295
9296            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9297                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9298                    // We just determined the app is signed correctly, so bring
9299                    // over the latest parsed certs.
9300                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9301                } else {
9302                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9303                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9304                                "Package " + pkg.packageName + " upgrade keys do not match the "
9305                                + "previously installed version");
9306                    } else {
9307                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9308                        String msg = "System package " + pkg.packageName
9309                                + " signature changed; retaining data.";
9310                        reportSettingsProblem(Log.WARN, msg);
9311                    }
9312                }
9313            } else {
9314                try {
9315                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9316                    verifySignaturesLP(signatureCheckPs, pkg);
9317                    // We just determined the app is signed correctly, so bring
9318                    // over the latest parsed certs.
9319                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9320                } catch (PackageManagerException e) {
9321                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9322                        throw e;
9323                    }
9324                    // The signature has changed, but this package is in the system
9325                    // image...  let's recover!
9326                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9327                    // However...  if this package is part of a shared user, but it
9328                    // doesn't match the signature of the shared user, let's fail.
9329                    // What this means is that you can't change the signatures
9330                    // associated with an overall shared user, which doesn't seem all
9331                    // that unreasonable.
9332                    if (signatureCheckPs.sharedUser != null) {
9333                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9334                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9335                            throw new PackageManagerException(
9336                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9337                                    "Signature mismatch for shared user: "
9338                                            + pkgSetting.sharedUser);
9339                        }
9340                    }
9341                    // File a report about this.
9342                    String msg = "System package " + pkg.packageName
9343                            + " signature changed; retaining data.";
9344                    reportSettingsProblem(Log.WARN, msg);
9345                }
9346            }
9347
9348            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9349                // This package wants to adopt ownership of permissions from
9350                // another package.
9351                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9352                    final String origName = pkg.mAdoptPermissions.get(i);
9353                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9354                    if (orig != null) {
9355                        if (verifyPackageUpdateLPr(orig, pkg)) {
9356                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9357                                    + pkg.packageName);
9358                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9359                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9360                        }
9361                    }
9362                }
9363            }
9364        }
9365
9366        pkg.applicationInfo.processName = fixProcessName(
9367                pkg.applicationInfo.packageName,
9368                pkg.applicationInfo.processName);
9369
9370        if (pkg != mPlatformPackage) {
9371            // Get all of our default paths setup
9372            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9373        }
9374
9375        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9376
9377        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9378            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9379                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9380                derivePackageAbi(
9381                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9382                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9383
9384                // Some system apps still use directory structure for native libraries
9385                // in which case we might end up not detecting abi solely based on apk
9386                // structure. Try to detect abi based on directory structure.
9387                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9388                        pkg.applicationInfo.primaryCpuAbi == null) {
9389                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9390                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9391                }
9392            } else {
9393                // This is not a first boot or an upgrade, don't bother deriving the
9394                // ABI during the scan. Instead, trust the value that was stored in the
9395                // package setting.
9396                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9397                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9398
9399                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9400
9401                if (DEBUG_ABI_SELECTION) {
9402                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9403                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9404                        pkg.applicationInfo.secondaryCpuAbi);
9405                }
9406            }
9407        } else {
9408            if ((scanFlags & SCAN_MOVE) != 0) {
9409                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9410                // but we already have this packages package info in the PackageSetting. We just
9411                // use that and derive the native library path based on the new codepath.
9412                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9413                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9414            }
9415
9416            // Set native library paths again. For moves, the path will be updated based on the
9417            // ABIs we've determined above. For non-moves, the path will be updated based on the
9418            // ABIs we determined during compilation, but the path will depend on the final
9419            // package path (after the rename away from the stage path).
9420            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9421        }
9422
9423        // This is a special case for the "system" package, where the ABI is
9424        // dictated by the zygote configuration (and init.rc). We should keep track
9425        // of this ABI so that we can deal with "normal" applications that run under
9426        // the same UID correctly.
9427        if (mPlatformPackage == pkg) {
9428            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9429                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9430        }
9431
9432        // If there's a mismatch between the abi-override in the package setting
9433        // and the abiOverride specified for the install. Warn about this because we
9434        // would've already compiled the app without taking the package setting into
9435        // account.
9436        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9437            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9438                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9439                        " for package " + pkg.packageName);
9440            }
9441        }
9442
9443        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9444        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9445        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9446
9447        // Copy the derived override back to the parsed package, so that we can
9448        // update the package settings accordingly.
9449        pkg.cpuAbiOverride = cpuAbiOverride;
9450
9451        if (DEBUG_ABI_SELECTION) {
9452            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9453                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9454                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9455        }
9456
9457        // Push the derived path down into PackageSettings so we know what to
9458        // clean up at uninstall time.
9459        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9460
9461        if (DEBUG_ABI_SELECTION) {
9462            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9463                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9464                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9465        }
9466
9467        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9468        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9469            // We don't do this here during boot because we can do it all
9470            // at once after scanning all existing packages.
9471            //
9472            // We also do this *before* we perform dexopt on this package, so that
9473            // we can avoid redundant dexopts, and also to make sure we've got the
9474            // code and package path correct.
9475            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9476        }
9477
9478        if (mFactoryTest && pkg.requestedPermissions.contains(
9479                android.Manifest.permission.FACTORY_TEST)) {
9480            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9481        }
9482
9483        if (isSystemApp(pkg)) {
9484            pkgSetting.isOrphaned = true;
9485        }
9486
9487        // Take care of first install / last update times.
9488        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9489        if (currentTime != 0) {
9490            if (pkgSetting.firstInstallTime == 0) {
9491                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9492            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9493                pkgSetting.lastUpdateTime = currentTime;
9494            }
9495        } else if (pkgSetting.firstInstallTime == 0) {
9496            // We need *something*.  Take time time stamp of the file.
9497            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9498        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9499            if (scanFileTime != pkgSetting.timeStamp) {
9500                // A package on the system image has changed; consider this
9501                // to be an update.
9502                pkgSetting.lastUpdateTime = scanFileTime;
9503            }
9504        }
9505        pkgSetting.setTimeStamp(scanFileTime);
9506
9507        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9508            if (nonMutatedPs != null) {
9509                synchronized (mPackages) {
9510                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9511                }
9512            }
9513        } else {
9514            final int userId = user == null ? 0 : user.getIdentifier();
9515            // Modify state for the given package setting
9516            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9517                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9518            if (pkgSetting.getInstantApp(userId)) {
9519                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9520            }
9521        }
9522        return pkg;
9523    }
9524
9525    /**
9526     * Applies policy to the parsed package based upon the given policy flags.
9527     * Ensures the package is in a good state.
9528     * <p>
9529     * Implementation detail: This method must NOT have any side effect. It would
9530     * ideally be static, but, it requires locks to read system state.
9531     */
9532    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9533        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9534            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9535            if (pkg.applicationInfo.isDirectBootAware()) {
9536                // we're direct boot aware; set for all components
9537                for (PackageParser.Service s : pkg.services) {
9538                    s.info.encryptionAware = s.info.directBootAware = true;
9539                }
9540                for (PackageParser.Provider p : pkg.providers) {
9541                    p.info.encryptionAware = p.info.directBootAware = true;
9542                }
9543                for (PackageParser.Activity a : pkg.activities) {
9544                    a.info.encryptionAware = a.info.directBootAware = true;
9545                }
9546                for (PackageParser.Activity r : pkg.receivers) {
9547                    r.info.encryptionAware = r.info.directBootAware = true;
9548                }
9549            }
9550        } else {
9551            // Only allow system apps to be flagged as core apps.
9552            pkg.coreApp = false;
9553            // clear flags not applicable to regular apps
9554            pkg.applicationInfo.privateFlags &=
9555                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9556            pkg.applicationInfo.privateFlags &=
9557                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9558        }
9559        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9560
9561        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9562            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9563        }
9564
9565        if (!isSystemApp(pkg)) {
9566            // Only system apps can use these features.
9567            pkg.mOriginalPackages = null;
9568            pkg.mRealPackage = null;
9569            pkg.mAdoptPermissions = null;
9570        }
9571    }
9572
9573    /**
9574     * Asserts the parsed package is valid according to the given policy. If the
9575     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9576     * <p>
9577     * Implementation detail: This method must NOT have any side effects. It would
9578     * ideally be static, but, it requires locks to read system state.
9579     *
9580     * @throws PackageManagerException If the package fails any of the validation checks
9581     */
9582    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9583            throws PackageManagerException {
9584        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9585            assertCodePolicy(pkg);
9586        }
9587
9588        if (pkg.applicationInfo.getCodePath() == null ||
9589                pkg.applicationInfo.getResourcePath() == null) {
9590            // Bail out. The resource and code paths haven't been set.
9591            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9592                    "Code and resource paths haven't been set correctly");
9593        }
9594
9595        // Make sure we're not adding any bogus keyset info
9596        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9597        ksms.assertScannedPackageValid(pkg);
9598
9599        synchronized (mPackages) {
9600            // The special "android" package can only be defined once
9601            if (pkg.packageName.equals("android")) {
9602                if (mAndroidApplication != null) {
9603                    Slog.w(TAG, "*************************************************");
9604                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9605                    Slog.w(TAG, " codePath=" + pkg.codePath);
9606                    Slog.w(TAG, "*************************************************");
9607                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9608                            "Core android package being redefined.  Skipping.");
9609                }
9610            }
9611
9612            // A package name must be unique; don't allow duplicates
9613            if (mPackages.containsKey(pkg.packageName)) {
9614                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9615                        "Application package " + pkg.packageName
9616                        + " already installed.  Skipping duplicate.");
9617            }
9618
9619            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9620                // Static libs have a synthetic package name containing the version
9621                // but we still want the base name to be unique.
9622                if (mPackages.containsKey(pkg.manifestPackageName)) {
9623                    throw new PackageManagerException(
9624                            "Duplicate static shared lib provider package");
9625                }
9626
9627                // Static shared libraries should have at least O target SDK
9628                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9629                    throw new PackageManagerException(
9630                            "Packages declaring static-shared libs must target O SDK or higher");
9631                }
9632
9633                // Package declaring static a shared lib cannot be instant apps
9634                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9635                    throw new PackageManagerException(
9636                            "Packages declaring static-shared libs cannot be instant apps");
9637                }
9638
9639                // Package declaring static a shared lib cannot be renamed since the package
9640                // name is synthetic and apps can't code around package manager internals.
9641                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9642                    throw new PackageManagerException(
9643                            "Packages declaring static-shared libs cannot be renamed");
9644                }
9645
9646                // Package declaring static a shared lib cannot declare child packages
9647                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9648                    throw new PackageManagerException(
9649                            "Packages declaring static-shared libs cannot have child packages");
9650                }
9651
9652                // Package declaring static a shared lib cannot declare dynamic libs
9653                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9654                    throw new PackageManagerException(
9655                            "Packages declaring static-shared libs cannot declare dynamic libs");
9656                }
9657
9658                // Package declaring static a shared lib cannot declare shared users
9659                if (pkg.mSharedUserId != null) {
9660                    throw new PackageManagerException(
9661                            "Packages declaring static-shared libs cannot declare shared users");
9662                }
9663
9664                // Static shared libs cannot declare activities
9665                if (!pkg.activities.isEmpty()) {
9666                    throw new PackageManagerException(
9667                            "Static shared libs cannot declare activities");
9668                }
9669
9670                // Static shared libs cannot declare services
9671                if (!pkg.services.isEmpty()) {
9672                    throw new PackageManagerException(
9673                            "Static shared libs cannot declare services");
9674                }
9675
9676                // Static shared libs cannot declare providers
9677                if (!pkg.providers.isEmpty()) {
9678                    throw new PackageManagerException(
9679                            "Static shared libs cannot declare content providers");
9680                }
9681
9682                // Static shared libs cannot declare receivers
9683                if (!pkg.receivers.isEmpty()) {
9684                    throw new PackageManagerException(
9685                            "Static shared libs cannot declare broadcast receivers");
9686                }
9687
9688                // Static shared libs cannot declare permission groups
9689                if (!pkg.permissionGroups.isEmpty()) {
9690                    throw new PackageManagerException(
9691                            "Static shared libs cannot declare permission groups");
9692                }
9693
9694                // Static shared libs cannot declare permissions
9695                if (!pkg.permissions.isEmpty()) {
9696                    throw new PackageManagerException(
9697                            "Static shared libs cannot declare permissions");
9698                }
9699
9700                // Static shared libs cannot declare protected broadcasts
9701                if (pkg.protectedBroadcasts != null) {
9702                    throw new PackageManagerException(
9703                            "Static shared libs cannot declare protected broadcasts");
9704                }
9705
9706                // Static shared libs cannot be overlay targets
9707                if (pkg.mOverlayTarget != null) {
9708                    throw new PackageManagerException(
9709                            "Static shared libs cannot be overlay targets");
9710                }
9711
9712                // The version codes must be ordered as lib versions
9713                int minVersionCode = Integer.MIN_VALUE;
9714                int maxVersionCode = Integer.MAX_VALUE;
9715
9716                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9717                        pkg.staticSharedLibName);
9718                if (versionedLib != null) {
9719                    final int versionCount = versionedLib.size();
9720                    for (int i = 0; i < versionCount; i++) {
9721                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9722                        // TODO: We will change version code to long, so in the new API it is long
9723                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9724                                .getVersionCode();
9725                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9726                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9727                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9728                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9729                        } else {
9730                            minVersionCode = maxVersionCode = libVersionCode;
9731                            break;
9732                        }
9733                    }
9734                }
9735                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9736                    throw new PackageManagerException("Static shared"
9737                            + " lib version codes must be ordered as lib versions");
9738                }
9739            }
9740
9741            // Only privileged apps and updated privileged apps can add child packages.
9742            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9743                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9744                    throw new PackageManagerException("Only privileged apps can add child "
9745                            + "packages. Ignoring package " + pkg.packageName);
9746                }
9747                final int childCount = pkg.childPackages.size();
9748                for (int i = 0; i < childCount; i++) {
9749                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9750                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9751                            childPkg.packageName)) {
9752                        throw new PackageManagerException("Can't override child of "
9753                                + "another disabled app. Ignoring package " + pkg.packageName);
9754                    }
9755                }
9756            }
9757
9758            // If we're only installing presumed-existing packages, require that the
9759            // scanned APK is both already known and at the path previously established
9760            // for it.  Previously unknown packages we pick up normally, but if we have an
9761            // a priori expectation about this package's install presence, enforce it.
9762            // With a singular exception for new system packages. When an OTA contains
9763            // a new system package, we allow the codepath to change from a system location
9764            // to the user-installed location. If we don't allow this change, any newer,
9765            // user-installed version of the application will be ignored.
9766            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9767                if (mExpectingBetter.containsKey(pkg.packageName)) {
9768                    logCriticalInfo(Log.WARN,
9769                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9770                } else {
9771                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9772                    if (known != null) {
9773                        if (DEBUG_PACKAGE_SCANNING) {
9774                            Log.d(TAG, "Examining " + pkg.codePath
9775                                    + " and requiring known paths " + known.codePathString
9776                                    + " & " + known.resourcePathString);
9777                        }
9778                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9779                                || !pkg.applicationInfo.getResourcePath().equals(
9780                                        known.resourcePathString)) {
9781                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9782                                    "Application package " + pkg.packageName
9783                                    + " found at " + pkg.applicationInfo.getCodePath()
9784                                    + " but expected at " + known.codePathString
9785                                    + "; ignoring.");
9786                        }
9787                    }
9788                }
9789            }
9790
9791            // Verify that this new package doesn't have any content providers
9792            // that conflict with existing packages.  Only do this if the
9793            // package isn't already installed, since we don't want to break
9794            // things that are installed.
9795            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9796                final int N = pkg.providers.size();
9797                int i;
9798                for (i=0; i<N; i++) {
9799                    PackageParser.Provider p = pkg.providers.get(i);
9800                    if (p.info.authority != null) {
9801                        String names[] = p.info.authority.split(";");
9802                        for (int j = 0; j < names.length; j++) {
9803                            if (mProvidersByAuthority.containsKey(names[j])) {
9804                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9805                                final String otherPackageName =
9806                                        ((other != null && other.getComponentName() != null) ?
9807                                                other.getComponentName().getPackageName() : "?");
9808                                throw new PackageManagerException(
9809                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9810                                        "Can't install because provider name " + names[j]
9811                                                + " (in package " + pkg.applicationInfo.packageName
9812                                                + ") is already used by " + otherPackageName);
9813                            }
9814                        }
9815                    }
9816                }
9817            }
9818        }
9819    }
9820
9821    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9822            int type, String declaringPackageName, int declaringVersionCode) {
9823        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9824        if (versionedLib == null) {
9825            versionedLib = new SparseArray<>();
9826            mSharedLibraries.put(name, versionedLib);
9827            if (type == SharedLibraryInfo.TYPE_STATIC) {
9828                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9829            }
9830        } else if (versionedLib.indexOfKey(version) >= 0) {
9831            return false;
9832        }
9833        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9834                version, type, declaringPackageName, declaringVersionCode);
9835        versionedLib.put(version, libEntry);
9836        return true;
9837    }
9838
9839    private boolean removeSharedLibraryLPw(String name, int version) {
9840        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9841        if (versionedLib == null) {
9842            return false;
9843        }
9844        final int libIdx = versionedLib.indexOfKey(version);
9845        if (libIdx < 0) {
9846            return false;
9847        }
9848        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9849        versionedLib.remove(version);
9850        if (versionedLib.size() <= 0) {
9851            mSharedLibraries.remove(name);
9852            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9853                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9854                        .getPackageName());
9855            }
9856        }
9857        return true;
9858    }
9859
9860    /**
9861     * Adds a scanned package to the system. When this method is finished, the package will
9862     * be available for query, resolution, etc...
9863     */
9864    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9865            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9866        final String pkgName = pkg.packageName;
9867        if (mCustomResolverComponentName != null &&
9868                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9869            setUpCustomResolverActivity(pkg);
9870        }
9871
9872        if (pkg.packageName.equals("android")) {
9873            synchronized (mPackages) {
9874                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9875                    // Set up information for our fall-back user intent resolution activity.
9876                    mPlatformPackage = pkg;
9877                    pkg.mVersionCode = mSdkVersion;
9878                    mAndroidApplication = pkg.applicationInfo;
9879                    if (!mResolverReplaced) {
9880                        mResolveActivity.applicationInfo = mAndroidApplication;
9881                        mResolveActivity.name = ResolverActivity.class.getName();
9882                        mResolveActivity.packageName = mAndroidApplication.packageName;
9883                        mResolveActivity.processName = "system:ui";
9884                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9885                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9886                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9887                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9888                        mResolveActivity.exported = true;
9889                        mResolveActivity.enabled = true;
9890                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9891                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9892                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9893                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9894                                | ActivityInfo.CONFIG_ORIENTATION
9895                                | ActivityInfo.CONFIG_KEYBOARD
9896                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9897                        mResolveInfo.activityInfo = mResolveActivity;
9898                        mResolveInfo.priority = 0;
9899                        mResolveInfo.preferredOrder = 0;
9900                        mResolveInfo.match = 0;
9901                        mResolveComponentName = new ComponentName(
9902                                mAndroidApplication.packageName, mResolveActivity.name);
9903                    }
9904                }
9905            }
9906        }
9907
9908        ArrayList<PackageParser.Package> clientLibPkgs = null;
9909        // writer
9910        synchronized (mPackages) {
9911            boolean hasStaticSharedLibs = false;
9912
9913            // Any app can add new static shared libraries
9914            if (pkg.staticSharedLibName != null) {
9915                // Static shared libs don't allow renaming as they have synthetic package
9916                // names to allow install of multiple versions, so use name from manifest.
9917                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9918                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9919                        pkg.manifestPackageName, pkg.mVersionCode)) {
9920                    hasStaticSharedLibs = true;
9921                } else {
9922                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9923                                + pkg.staticSharedLibName + " already exists; skipping");
9924                }
9925                // Static shared libs cannot be updated once installed since they
9926                // use synthetic package name which includes the version code, so
9927                // not need to update other packages's shared lib dependencies.
9928            }
9929
9930            if (!hasStaticSharedLibs
9931                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9932                // Only system apps can add new dynamic shared libraries.
9933                if (pkg.libraryNames != null) {
9934                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9935                        String name = pkg.libraryNames.get(i);
9936                        boolean allowed = false;
9937                        if (pkg.isUpdatedSystemApp()) {
9938                            // New library entries can only be added through the
9939                            // system image.  This is important to get rid of a lot
9940                            // of nasty edge cases: for example if we allowed a non-
9941                            // system update of the app to add a library, then uninstalling
9942                            // the update would make the library go away, and assumptions
9943                            // we made such as through app install filtering would now
9944                            // have allowed apps on the device which aren't compatible
9945                            // with it.  Better to just have the restriction here, be
9946                            // conservative, and create many fewer cases that can negatively
9947                            // impact the user experience.
9948                            final PackageSetting sysPs = mSettings
9949                                    .getDisabledSystemPkgLPr(pkg.packageName);
9950                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9951                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9952                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9953                                        allowed = true;
9954                                        break;
9955                                    }
9956                                }
9957                            }
9958                        } else {
9959                            allowed = true;
9960                        }
9961                        if (allowed) {
9962                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9963                                    SharedLibraryInfo.VERSION_UNDEFINED,
9964                                    SharedLibraryInfo.TYPE_DYNAMIC,
9965                                    pkg.packageName, pkg.mVersionCode)) {
9966                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9967                                        + name + " already exists; skipping");
9968                            }
9969                        } else {
9970                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9971                                    + name + " that is not declared on system image; skipping");
9972                        }
9973                    }
9974
9975                    if ((scanFlags & SCAN_BOOTING) == 0) {
9976                        // If we are not booting, we need to update any applications
9977                        // that are clients of our shared library.  If we are booting,
9978                        // this will all be done once the scan is complete.
9979                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9980                    }
9981                }
9982            }
9983        }
9984
9985        if ((scanFlags & SCAN_BOOTING) != 0) {
9986            // No apps can run during boot scan, so they don't need to be frozen
9987        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9988            // Caller asked to not kill app, so it's probably not frozen
9989        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9990            // Caller asked us to ignore frozen check for some reason; they
9991            // probably didn't know the package name
9992        } else {
9993            // We're doing major surgery on this package, so it better be frozen
9994            // right now to keep it from launching
9995            checkPackageFrozen(pkgName);
9996        }
9997
9998        // Also need to kill any apps that are dependent on the library.
9999        if (clientLibPkgs != null) {
10000            for (int i=0; i<clientLibPkgs.size(); i++) {
10001                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10002                killApplication(clientPkg.applicationInfo.packageName,
10003                        clientPkg.applicationInfo.uid, "update lib");
10004            }
10005        }
10006
10007        // writer
10008        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10009
10010        synchronized (mPackages) {
10011            // We don't expect installation to fail beyond this point
10012
10013            // Add the new setting to mSettings
10014            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10015            // Add the new setting to mPackages
10016            mPackages.put(pkg.applicationInfo.packageName, pkg);
10017            // Make sure we don't accidentally delete its data.
10018            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10019            while (iter.hasNext()) {
10020                PackageCleanItem item = iter.next();
10021                if (pkgName.equals(item.packageName)) {
10022                    iter.remove();
10023                }
10024            }
10025
10026            // Add the package's KeySets to the global KeySetManagerService
10027            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10028            ksms.addScannedPackageLPw(pkg);
10029
10030            int N = pkg.providers.size();
10031            StringBuilder r = null;
10032            int i;
10033            for (i=0; i<N; i++) {
10034                PackageParser.Provider p = pkg.providers.get(i);
10035                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10036                        p.info.processName);
10037                mProviders.addProvider(p);
10038                p.syncable = p.info.isSyncable;
10039                if (p.info.authority != null) {
10040                    String names[] = p.info.authority.split(";");
10041                    p.info.authority = null;
10042                    for (int j = 0; j < names.length; j++) {
10043                        if (j == 1 && p.syncable) {
10044                            // We only want the first authority for a provider to possibly be
10045                            // syncable, so if we already added this provider using a different
10046                            // authority clear the syncable flag. We copy the provider before
10047                            // changing it because the mProviders object contains a reference
10048                            // to a provider that we don't want to change.
10049                            // Only do this for the second authority since the resulting provider
10050                            // object can be the same for all future authorities for this provider.
10051                            p = new PackageParser.Provider(p);
10052                            p.syncable = false;
10053                        }
10054                        if (!mProvidersByAuthority.containsKey(names[j])) {
10055                            mProvidersByAuthority.put(names[j], p);
10056                            if (p.info.authority == null) {
10057                                p.info.authority = names[j];
10058                            } else {
10059                                p.info.authority = p.info.authority + ";" + names[j];
10060                            }
10061                            if (DEBUG_PACKAGE_SCANNING) {
10062                                if (chatty)
10063                                    Log.d(TAG, "Registered content provider: " + names[j]
10064                                            + ", className = " + p.info.name + ", isSyncable = "
10065                                            + p.info.isSyncable);
10066                            }
10067                        } else {
10068                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10069                            Slog.w(TAG, "Skipping provider name " + names[j] +
10070                                    " (in package " + pkg.applicationInfo.packageName +
10071                                    "): name already used by "
10072                                    + ((other != null && other.getComponentName() != null)
10073                                            ? other.getComponentName().getPackageName() : "?"));
10074                        }
10075                    }
10076                }
10077                if (chatty) {
10078                    if (r == null) {
10079                        r = new StringBuilder(256);
10080                    } else {
10081                        r.append(' ');
10082                    }
10083                    r.append(p.info.name);
10084                }
10085            }
10086            if (r != null) {
10087                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10088            }
10089
10090            N = pkg.services.size();
10091            r = null;
10092            for (i=0; i<N; i++) {
10093                PackageParser.Service s = pkg.services.get(i);
10094                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10095                        s.info.processName);
10096                mServices.addService(s);
10097                if (chatty) {
10098                    if (r == null) {
10099                        r = new StringBuilder(256);
10100                    } else {
10101                        r.append(' ');
10102                    }
10103                    r.append(s.info.name);
10104                }
10105            }
10106            if (r != null) {
10107                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10108            }
10109
10110            N = pkg.receivers.size();
10111            r = null;
10112            for (i=0; i<N; i++) {
10113                PackageParser.Activity a = pkg.receivers.get(i);
10114                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10115                        a.info.processName);
10116                mReceivers.addActivity(a, "receiver");
10117                if (chatty) {
10118                    if (r == null) {
10119                        r = new StringBuilder(256);
10120                    } else {
10121                        r.append(' ');
10122                    }
10123                    r.append(a.info.name);
10124                }
10125            }
10126            if (r != null) {
10127                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10128            }
10129
10130            N = pkg.activities.size();
10131            r = null;
10132            for (i=0; i<N; i++) {
10133                PackageParser.Activity a = pkg.activities.get(i);
10134                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10135                        a.info.processName);
10136                mActivities.addActivity(a, "activity");
10137                if (chatty) {
10138                    if (r == null) {
10139                        r = new StringBuilder(256);
10140                    } else {
10141                        r.append(' ');
10142                    }
10143                    r.append(a.info.name);
10144                }
10145            }
10146            if (r != null) {
10147                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10148            }
10149
10150            N = pkg.permissionGroups.size();
10151            r = null;
10152            for (i=0; i<N; i++) {
10153                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10154                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10155                final String curPackageName = cur == null ? null : cur.info.packageName;
10156                // Dont allow ephemeral apps to define new permission groups.
10157                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10158                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10159                            + pg.info.packageName
10160                            + " ignored: instant apps cannot define new permission groups.");
10161                    continue;
10162                }
10163                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10164                if (cur == null || isPackageUpdate) {
10165                    mPermissionGroups.put(pg.info.name, pg);
10166                    if (chatty) {
10167                        if (r == null) {
10168                            r = new StringBuilder(256);
10169                        } else {
10170                            r.append(' ');
10171                        }
10172                        if (isPackageUpdate) {
10173                            r.append("UPD:");
10174                        }
10175                        r.append(pg.info.name);
10176                    }
10177                } else {
10178                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10179                            + pg.info.packageName + " ignored: original from "
10180                            + cur.info.packageName);
10181                    if (chatty) {
10182                        if (r == null) {
10183                            r = new StringBuilder(256);
10184                        } else {
10185                            r.append(' ');
10186                        }
10187                        r.append("DUP:");
10188                        r.append(pg.info.name);
10189                    }
10190                }
10191            }
10192            if (r != null) {
10193                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10194            }
10195
10196            N = pkg.permissions.size();
10197            r = null;
10198            for (i=0; i<N; i++) {
10199                PackageParser.Permission p = pkg.permissions.get(i);
10200
10201                // Dont allow ephemeral apps to define new permissions.
10202                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10203                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10204                            + p.info.packageName
10205                            + " ignored: instant apps cannot define new permissions.");
10206                    continue;
10207                }
10208
10209                // Assume by default that we did not install this permission into the system.
10210                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10211
10212                // Now that permission groups have a special meaning, we ignore permission
10213                // groups for legacy apps to prevent unexpected behavior. In particular,
10214                // permissions for one app being granted to someone just becase they happen
10215                // to be in a group defined by another app (before this had no implications).
10216                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10217                    p.group = mPermissionGroups.get(p.info.group);
10218                    // Warn for a permission in an unknown group.
10219                    if (p.info.group != null && p.group == null) {
10220                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10221                                + p.info.packageName + " in an unknown group " + p.info.group);
10222                    }
10223                }
10224
10225                ArrayMap<String, BasePermission> permissionMap =
10226                        p.tree ? mSettings.mPermissionTrees
10227                                : mSettings.mPermissions;
10228                BasePermission bp = permissionMap.get(p.info.name);
10229
10230                // Allow system apps to redefine non-system permissions
10231                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10232                    final boolean currentOwnerIsSystem = (bp.perm != null
10233                            && isSystemApp(bp.perm.owner));
10234                    if (isSystemApp(p.owner)) {
10235                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10236                            // It's a built-in permission and no owner, take ownership now
10237                            bp.packageSetting = pkgSetting;
10238                            bp.perm = p;
10239                            bp.uid = pkg.applicationInfo.uid;
10240                            bp.sourcePackage = p.info.packageName;
10241                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10242                        } else if (!currentOwnerIsSystem) {
10243                            String msg = "New decl " + p.owner + " of permission  "
10244                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10245                            reportSettingsProblem(Log.WARN, msg);
10246                            bp = null;
10247                        }
10248                    }
10249                }
10250
10251                if (bp == null) {
10252                    bp = new BasePermission(p.info.name, p.info.packageName,
10253                            BasePermission.TYPE_NORMAL);
10254                    permissionMap.put(p.info.name, bp);
10255                }
10256
10257                if (bp.perm == null) {
10258                    if (bp.sourcePackage == null
10259                            || bp.sourcePackage.equals(p.info.packageName)) {
10260                        BasePermission tree = findPermissionTreeLP(p.info.name);
10261                        if (tree == null
10262                                || tree.sourcePackage.equals(p.info.packageName)) {
10263                            bp.packageSetting = pkgSetting;
10264                            bp.perm = p;
10265                            bp.uid = pkg.applicationInfo.uid;
10266                            bp.sourcePackage = p.info.packageName;
10267                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10268                            if (chatty) {
10269                                if (r == null) {
10270                                    r = new StringBuilder(256);
10271                                } else {
10272                                    r.append(' ');
10273                                }
10274                                r.append(p.info.name);
10275                            }
10276                        } else {
10277                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10278                                    + p.info.packageName + " ignored: base tree "
10279                                    + tree.name + " is from package "
10280                                    + tree.sourcePackage);
10281                        }
10282                    } else {
10283                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10284                                + p.info.packageName + " ignored: original from "
10285                                + bp.sourcePackage);
10286                    }
10287                } else if (chatty) {
10288                    if (r == null) {
10289                        r = new StringBuilder(256);
10290                    } else {
10291                        r.append(' ');
10292                    }
10293                    r.append("DUP:");
10294                    r.append(p.info.name);
10295                }
10296                if (bp.perm == p) {
10297                    bp.protectionLevel = p.info.protectionLevel;
10298                }
10299            }
10300
10301            if (r != null) {
10302                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10303            }
10304
10305            N = pkg.instrumentation.size();
10306            r = null;
10307            for (i=0; i<N; i++) {
10308                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10309                a.info.packageName = pkg.applicationInfo.packageName;
10310                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10311                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10312                a.info.splitNames = pkg.splitNames;
10313                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10314                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10315                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10316                a.info.dataDir = pkg.applicationInfo.dataDir;
10317                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10318                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10319                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10320                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10321                mInstrumentation.put(a.getComponentName(), a);
10322                if (chatty) {
10323                    if (r == null) {
10324                        r = new StringBuilder(256);
10325                    } else {
10326                        r.append(' ');
10327                    }
10328                    r.append(a.info.name);
10329                }
10330            }
10331            if (r != null) {
10332                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10333            }
10334
10335            if (pkg.protectedBroadcasts != null) {
10336                N = pkg.protectedBroadcasts.size();
10337                for (i=0; i<N; i++) {
10338                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10339                }
10340            }
10341        }
10342
10343        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10344    }
10345
10346    /**
10347     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10348     * is derived purely on the basis of the contents of {@code scanFile} and
10349     * {@code cpuAbiOverride}.
10350     *
10351     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10352     */
10353    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10354                                 String cpuAbiOverride, boolean extractLibs,
10355                                 File appLib32InstallDir)
10356            throws PackageManagerException {
10357        // Give ourselves some initial paths; we'll come back for another
10358        // pass once we've determined ABI below.
10359        setNativeLibraryPaths(pkg, appLib32InstallDir);
10360
10361        // We would never need to extract libs for forward-locked and external packages,
10362        // since the container service will do it for us. We shouldn't attempt to
10363        // extract libs from system app when it was not updated.
10364        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10365                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10366            extractLibs = false;
10367        }
10368
10369        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10370        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10371
10372        NativeLibraryHelper.Handle handle = null;
10373        try {
10374            handle = NativeLibraryHelper.Handle.create(pkg);
10375            // TODO(multiArch): This can be null for apps that didn't go through the
10376            // usual installation process. We can calculate it again, like we
10377            // do during install time.
10378            //
10379            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10380            // unnecessary.
10381            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10382
10383            // Null out the abis so that they can be recalculated.
10384            pkg.applicationInfo.primaryCpuAbi = null;
10385            pkg.applicationInfo.secondaryCpuAbi = null;
10386            if (isMultiArch(pkg.applicationInfo)) {
10387                // Warn if we've set an abiOverride for multi-lib packages..
10388                // By definition, we need to copy both 32 and 64 bit libraries for
10389                // such packages.
10390                if (pkg.cpuAbiOverride != null
10391                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10392                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10393                }
10394
10395                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10396                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10397                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10398                    if (extractLibs) {
10399                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10400                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10401                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10402                                useIsaSpecificSubdirs);
10403                    } else {
10404                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10405                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10406                    }
10407                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10408                }
10409
10410                maybeThrowExceptionForMultiArchCopy(
10411                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10412
10413                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10414                    if (extractLibs) {
10415                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10416                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10417                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10418                                useIsaSpecificSubdirs);
10419                    } else {
10420                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10421                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10422                    }
10423                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10424                }
10425
10426                maybeThrowExceptionForMultiArchCopy(
10427                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10428
10429                if (abi64 >= 0) {
10430                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10431                }
10432
10433                if (abi32 >= 0) {
10434                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10435                    if (abi64 >= 0) {
10436                        if (pkg.use32bitAbi) {
10437                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10438                            pkg.applicationInfo.primaryCpuAbi = abi;
10439                        } else {
10440                            pkg.applicationInfo.secondaryCpuAbi = abi;
10441                        }
10442                    } else {
10443                        pkg.applicationInfo.primaryCpuAbi = abi;
10444                    }
10445                }
10446
10447            } else {
10448                String[] abiList = (cpuAbiOverride != null) ?
10449                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10450
10451                // Enable gross and lame hacks for apps that are built with old
10452                // SDK tools. We must scan their APKs for renderscript bitcode and
10453                // not launch them if it's present. Don't bother checking on devices
10454                // that don't have 64 bit support.
10455                boolean needsRenderScriptOverride = false;
10456                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10457                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10458                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10459                    needsRenderScriptOverride = true;
10460                }
10461
10462                final int copyRet;
10463                if (extractLibs) {
10464                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10465                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10466                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10467                } else {
10468                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10469                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10470                }
10471                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10472
10473                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10474                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10475                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10476                }
10477
10478                if (copyRet >= 0) {
10479                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10480                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10481                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10482                } else if (needsRenderScriptOverride) {
10483                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10484                }
10485            }
10486        } catch (IOException ioe) {
10487            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10488        } finally {
10489            IoUtils.closeQuietly(handle);
10490        }
10491
10492        // Now that we've calculated the ABIs and determined if it's an internal app,
10493        // we will go ahead and populate the nativeLibraryPath.
10494        setNativeLibraryPaths(pkg, appLib32InstallDir);
10495    }
10496
10497    /**
10498     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10499     * i.e, so that all packages can be run inside a single process if required.
10500     *
10501     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10502     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10503     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10504     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10505     * updating a package that belongs to a shared user.
10506     *
10507     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10508     * adds unnecessary complexity.
10509     */
10510    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10511            PackageParser.Package scannedPackage) {
10512        String requiredInstructionSet = null;
10513        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10514            requiredInstructionSet = VMRuntime.getInstructionSet(
10515                     scannedPackage.applicationInfo.primaryCpuAbi);
10516        }
10517
10518        PackageSetting requirer = null;
10519        for (PackageSetting ps : packagesForUser) {
10520            // If packagesForUser contains scannedPackage, we skip it. This will happen
10521            // when scannedPackage is an update of an existing package. Without this check,
10522            // we will never be able to change the ABI of any package belonging to a shared
10523            // user, even if it's compatible with other packages.
10524            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10525                if (ps.primaryCpuAbiString == null) {
10526                    continue;
10527                }
10528
10529                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10530                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10531                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10532                    // this but there's not much we can do.
10533                    String errorMessage = "Instruction set mismatch, "
10534                            + ((requirer == null) ? "[caller]" : requirer)
10535                            + " requires " + requiredInstructionSet + " whereas " + ps
10536                            + " requires " + instructionSet;
10537                    Slog.w(TAG, errorMessage);
10538                }
10539
10540                if (requiredInstructionSet == null) {
10541                    requiredInstructionSet = instructionSet;
10542                    requirer = ps;
10543                }
10544            }
10545        }
10546
10547        if (requiredInstructionSet != null) {
10548            String adjustedAbi;
10549            if (requirer != null) {
10550                // requirer != null implies that either scannedPackage was null or that scannedPackage
10551                // did not require an ABI, in which case we have to adjust scannedPackage to match
10552                // the ABI of the set (which is the same as requirer's ABI)
10553                adjustedAbi = requirer.primaryCpuAbiString;
10554                if (scannedPackage != null) {
10555                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10556                }
10557            } else {
10558                // requirer == null implies that we're updating all ABIs in the set to
10559                // match scannedPackage.
10560                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10561            }
10562
10563            for (PackageSetting ps : packagesForUser) {
10564                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10565                    if (ps.primaryCpuAbiString != null) {
10566                        continue;
10567                    }
10568
10569                    ps.primaryCpuAbiString = adjustedAbi;
10570                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10571                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10572                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10573                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10574                                + " (requirer="
10575                                + (requirer != null ? requirer.pkg : "null")
10576                                + ", scannedPackage="
10577                                + (scannedPackage != null ? scannedPackage : "null")
10578                                + ")");
10579                        try {
10580                            mInstaller.rmdex(ps.codePathString,
10581                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10582                        } catch (InstallerException ignored) {
10583                        }
10584                    }
10585                }
10586            }
10587        }
10588    }
10589
10590    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10591        synchronized (mPackages) {
10592            mResolverReplaced = true;
10593            // Set up information for custom user intent resolution activity.
10594            mResolveActivity.applicationInfo = pkg.applicationInfo;
10595            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10596            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10597            mResolveActivity.processName = pkg.applicationInfo.packageName;
10598            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10599            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10600                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10601            mResolveActivity.theme = 0;
10602            mResolveActivity.exported = true;
10603            mResolveActivity.enabled = true;
10604            mResolveInfo.activityInfo = mResolveActivity;
10605            mResolveInfo.priority = 0;
10606            mResolveInfo.preferredOrder = 0;
10607            mResolveInfo.match = 0;
10608            mResolveComponentName = mCustomResolverComponentName;
10609            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10610                    mResolveComponentName);
10611        }
10612    }
10613
10614    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10615        if (installerActivity == null) {
10616            if (DEBUG_EPHEMERAL) {
10617                Slog.d(TAG, "Clear ephemeral installer activity");
10618            }
10619            mInstantAppInstallerActivity = null;
10620            return;
10621        }
10622
10623        if (DEBUG_EPHEMERAL) {
10624            Slog.d(TAG, "Set ephemeral installer activity: "
10625                    + installerActivity.getComponentName());
10626        }
10627        // Set up information for ephemeral installer activity
10628        mInstantAppInstallerActivity = installerActivity;
10629        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10630                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10631        mInstantAppInstallerActivity.exported = true;
10632        mInstantAppInstallerActivity.enabled = true;
10633        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10634        mInstantAppInstallerInfo.priority = 0;
10635        mInstantAppInstallerInfo.preferredOrder = 1;
10636        mInstantAppInstallerInfo.isDefault = true;
10637        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10638                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10639    }
10640
10641    private static String calculateBundledApkRoot(final String codePathString) {
10642        final File codePath = new File(codePathString);
10643        final File codeRoot;
10644        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10645            codeRoot = Environment.getRootDirectory();
10646        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10647            codeRoot = Environment.getOemDirectory();
10648        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10649            codeRoot = Environment.getVendorDirectory();
10650        } else {
10651            // Unrecognized code path; take its top real segment as the apk root:
10652            // e.g. /something/app/blah.apk => /something
10653            try {
10654                File f = codePath.getCanonicalFile();
10655                File parent = f.getParentFile();    // non-null because codePath is a file
10656                File tmp;
10657                while ((tmp = parent.getParentFile()) != null) {
10658                    f = parent;
10659                    parent = tmp;
10660                }
10661                codeRoot = f;
10662                Slog.w(TAG, "Unrecognized code path "
10663                        + codePath + " - using " + codeRoot);
10664            } catch (IOException e) {
10665                // Can't canonicalize the code path -- shenanigans?
10666                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10667                return Environment.getRootDirectory().getPath();
10668            }
10669        }
10670        return codeRoot.getPath();
10671    }
10672
10673    /**
10674     * Derive and set the location of native libraries for the given package,
10675     * which varies depending on where and how the package was installed.
10676     */
10677    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10678        final ApplicationInfo info = pkg.applicationInfo;
10679        final String codePath = pkg.codePath;
10680        final File codeFile = new File(codePath);
10681        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10682        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10683
10684        info.nativeLibraryRootDir = null;
10685        info.nativeLibraryRootRequiresIsa = false;
10686        info.nativeLibraryDir = null;
10687        info.secondaryNativeLibraryDir = null;
10688
10689        if (isApkFile(codeFile)) {
10690            // Monolithic install
10691            if (bundledApp) {
10692                // If "/system/lib64/apkname" exists, assume that is the per-package
10693                // native library directory to use; otherwise use "/system/lib/apkname".
10694                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10695                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10696                        getPrimaryInstructionSet(info));
10697
10698                // This is a bundled system app so choose the path based on the ABI.
10699                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10700                // is just the default path.
10701                final String apkName = deriveCodePathName(codePath);
10702                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10703                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10704                        apkName).getAbsolutePath();
10705
10706                if (info.secondaryCpuAbi != null) {
10707                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10708                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10709                            secondaryLibDir, apkName).getAbsolutePath();
10710                }
10711            } else if (asecApp) {
10712                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10713                        .getAbsolutePath();
10714            } else {
10715                final String apkName = deriveCodePathName(codePath);
10716                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10717                        .getAbsolutePath();
10718            }
10719
10720            info.nativeLibraryRootRequiresIsa = false;
10721            info.nativeLibraryDir = info.nativeLibraryRootDir;
10722        } else {
10723            // Cluster install
10724            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10725            info.nativeLibraryRootRequiresIsa = true;
10726
10727            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10728                    getPrimaryInstructionSet(info)).getAbsolutePath();
10729
10730            if (info.secondaryCpuAbi != null) {
10731                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10732                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10733            }
10734        }
10735    }
10736
10737    /**
10738     * Calculate the abis and roots for a bundled app. These can uniquely
10739     * be determined from the contents of the system partition, i.e whether
10740     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10741     * of this information, and instead assume that the system was built
10742     * sensibly.
10743     */
10744    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10745                                           PackageSetting pkgSetting) {
10746        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10747
10748        // If "/system/lib64/apkname" exists, assume that is the per-package
10749        // native library directory to use; otherwise use "/system/lib/apkname".
10750        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10751        setBundledAppAbi(pkg, apkRoot, apkName);
10752        // pkgSetting might be null during rescan following uninstall of updates
10753        // to a bundled app, so accommodate that possibility.  The settings in
10754        // that case will be established later from the parsed package.
10755        //
10756        // If the settings aren't null, sync them up with what we've just derived.
10757        // note that apkRoot isn't stored in the package settings.
10758        if (pkgSetting != null) {
10759            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10760            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10761        }
10762    }
10763
10764    /**
10765     * Deduces the ABI of a bundled app and sets the relevant fields on the
10766     * parsed pkg object.
10767     *
10768     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10769     *        under which system libraries are installed.
10770     * @param apkName the name of the installed package.
10771     */
10772    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10773        final File codeFile = new File(pkg.codePath);
10774
10775        final boolean has64BitLibs;
10776        final boolean has32BitLibs;
10777        if (isApkFile(codeFile)) {
10778            // Monolithic install
10779            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10780            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10781        } else {
10782            // Cluster install
10783            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10784            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10785                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10786                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10787                has64BitLibs = (new File(rootDir, isa)).exists();
10788            } else {
10789                has64BitLibs = false;
10790            }
10791            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10792                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10793                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10794                has32BitLibs = (new File(rootDir, isa)).exists();
10795            } else {
10796                has32BitLibs = false;
10797            }
10798        }
10799
10800        if (has64BitLibs && !has32BitLibs) {
10801            // The package has 64 bit libs, but not 32 bit libs. Its primary
10802            // ABI should be 64 bit. We can safely assume here that the bundled
10803            // native libraries correspond to the most preferred ABI in the list.
10804
10805            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10806            pkg.applicationInfo.secondaryCpuAbi = null;
10807        } else if (has32BitLibs && !has64BitLibs) {
10808            // The package has 32 bit libs but not 64 bit libs. Its primary
10809            // ABI should be 32 bit.
10810
10811            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10812            pkg.applicationInfo.secondaryCpuAbi = null;
10813        } else if (has32BitLibs && has64BitLibs) {
10814            // The application has both 64 and 32 bit bundled libraries. We check
10815            // here that the app declares multiArch support, and warn if it doesn't.
10816            //
10817            // We will be lenient here and record both ABIs. The primary will be the
10818            // ABI that's higher on the list, i.e, a device that's configured to prefer
10819            // 64 bit apps will see a 64 bit primary ABI,
10820
10821            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10822                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10823            }
10824
10825            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10826                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10827                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10828            } else {
10829                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10830                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10831            }
10832        } else {
10833            pkg.applicationInfo.primaryCpuAbi = null;
10834            pkg.applicationInfo.secondaryCpuAbi = null;
10835        }
10836    }
10837
10838    private void killApplication(String pkgName, int appId, String reason) {
10839        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10840    }
10841
10842    private void killApplication(String pkgName, int appId, int userId, String reason) {
10843        // Request the ActivityManager to kill the process(only for existing packages)
10844        // so that we do not end up in a confused state while the user is still using the older
10845        // version of the application while the new one gets installed.
10846        final long token = Binder.clearCallingIdentity();
10847        try {
10848            IActivityManager am = ActivityManager.getService();
10849            if (am != null) {
10850                try {
10851                    am.killApplication(pkgName, appId, userId, reason);
10852                } catch (RemoteException e) {
10853                }
10854            }
10855        } finally {
10856            Binder.restoreCallingIdentity(token);
10857        }
10858    }
10859
10860    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10861        // Remove the parent package setting
10862        PackageSetting ps = (PackageSetting) pkg.mExtras;
10863        if (ps != null) {
10864            removePackageLI(ps, chatty);
10865        }
10866        // Remove the child package setting
10867        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10868        for (int i = 0; i < childCount; i++) {
10869            PackageParser.Package childPkg = pkg.childPackages.get(i);
10870            ps = (PackageSetting) childPkg.mExtras;
10871            if (ps != null) {
10872                removePackageLI(ps, chatty);
10873            }
10874        }
10875    }
10876
10877    void removePackageLI(PackageSetting ps, boolean chatty) {
10878        if (DEBUG_INSTALL) {
10879            if (chatty)
10880                Log.d(TAG, "Removing package " + ps.name);
10881        }
10882
10883        // writer
10884        synchronized (mPackages) {
10885            mPackages.remove(ps.name);
10886            final PackageParser.Package pkg = ps.pkg;
10887            if (pkg != null) {
10888                cleanPackageDataStructuresLILPw(pkg, chatty);
10889            }
10890        }
10891    }
10892
10893    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10894        if (DEBUG_INSTALL) {
10895            if (chatty)
10896                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10897        }
10898
10899        // writer
10900        synchronized (mPackages) {
10901            // Remove the parent package
10902            mPackages.remove(pkg.applicationInfo.packageName);
10903            cleanPackageDataStructuresLILPw(pkg, chatty);
10904
10905            // Remove the child packages
10906            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10907            for (int i = 0; i < childCount; i++) {
10908                PackageParser.Package childPkg = pkg.childPackages.get(i);
10909                mPackages.remove(childPkg.applicationInfo.packageName);
10910                cleanPackageDataStructuresLILPw(childPkg, chatty);
10911            }
10912        }
10913    }
10914
10915    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10916        int N = pkg.providers.size();
10917        StringBuilder r = null;
10918        int i;
10919        for (i=0; i<N; i++) {
10920            PackageParser.Provider p = pkg.providers.get(i);
10921            mProviders.removeProvider(p);
10922            if (p.info.authority == null) {
10923
10924                /* There was another ContentProvider with this authority when
10925                 * this app was installed so this authority is null,
10926                 * Ignore it as we don't have to unregister the provider.
10927                 */
10928                continue;
10929            }
10930            String names[] = p.info.authority.split(";");
10931            for (int j = 0; j < names.length; j++) {
10932                if (mProvidersByAuthority.get(names[j]) == p) {
10933                    mProvidersByAuthority.remove(names[j]);
10934                    if (DEBUG_REMOVE) {
10935                        if (chatty)
10936                            Log.d(TAG, "Unregistered content provider: " + names[j]
10937                                    + ", className = " + p.info.name + ", isSyncable = "
10938                                    + p.info.isSyncable);
10939                    }
10940                }
10941            }
10942            if (DEBUG_REMOVE && chatty) {
10943                if (r == null) {
10944                    r = new StringBuilder(256);
10945                } else {
10946                    r.append(' ');
10947                }
10948                r.append(p.info.name);
10949            }
10950        }
10951        if (r != null) {
10952            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10953        }
10954
10955        N = pkg.services.size();
10956        r = null;
10957        for (i=0; i<N; i++) {
10958            PackageParser.Service s = pkg.services.get(i);
10959            mServices.removeService(s);
10960            if (chatty) {
10961                if (r == null) {
10962                    r = new StringBuilder(256);
10963                } else {
10964                    r.append(' ');
10965                }
10966                r.append(s.info.name);
10967            }
10968        }
10969        if (r != null) {
10970            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10971        }
10972
10973        N = pkg.receivers.size();
10974        r = null;
10975        for (i=0; i<N; i++) {
10976            PackageParser.Activity a = pkg.receivers.get(i);
10977            mReceivers.removeActivity(a, "receiver");
10978            if (DEBUG_REMOVE && chatty) {
10979                if (r == null) {
10980                    r = new StringBuilder(256);
10981                } else {
10982                    r.append(' ');
10983                }
10984                r.append(a.info.name);
10985            }
10986        }
10987        if (r != null) {
10988            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10989        }
10990
10991        N = pkg.activities.size();
10992        r = null;
10993        for (i=0; i<N; i++) {
10994            PackageParser.Activity a = pkg.activities.get(i);
10995            mActivities.removeActivity(a, "activity");
10996            if (DEBUG_REMOVE && chatty) {
10997                if (r == null) {
10998                    r = new StringBuilder(256);
10999                } else {
11000                    r.append(' ');
11001                }
11002                r.append(a.info.name);
11003            }
11004        }
11005        if (r != null) {
11006            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11007        }
11008
11009        N = pkg.permissions.size();
11010        r = null;
11011        for (i=0; i<N; i++) {
11012            PackageParser.Permission p = pkg.permissions.get(i);
11013            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11014            if (bp == null) {
11015                bp = mSettings.mPermissionTrees.get(p.info.name);
11016            }
11017            if (bp != null && bp.perm == p) {
11018                bp.perm = null;
11019                if (DEBUG_REMOVE && chatty) {
11020                    if (r == null) {
11021                        r = new StringBuilder(256);
11022                    } else {
11023                        r.append(' ');
11024                    }
11025                    r.append(p.info.name);
11026                }
11027            }
11028            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11029                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11030                if (appOpPkgs != null) {
11031                    appOpPkgs.remove(pkg.packageName);
11032                }
11033            }
11034        }
11035        if (r != null) {
11036            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11037        }
11038
11039        N = pkg.requestedPermissions.size();
11040        r = null;
11041        for (i=0; i<N; i++) {
11042            String perm = pkg.requestedPermissions.get(i);
11043            BasePermission bp = mSettings.mPermissions.get(perm);
11044            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11045                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11046                if (appOpPkgs != null) {
11047                    appOpPkgs.remove(pkg.packageName);
11048                    if (appOpPkgs.isEmpty()) {
11049                        mAppOpPermissionPackages.remove(perm);
11050                    }
11051                }
11052            }
11053        }
11054        if (r != null) {
11055            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11056        }
11057
11058        N = pkg.instrumentation.size();
11059        r = null;
11060        for (i=0; i<N; i++) {
11061            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11062            mInstrumentation.remove(a.getComponentName());
11063            if (DEBUG_REMOVE && chatty) {
11064                if (r == null) {
11065                    r = new StringBuilder(256);
11066                } else {
11067                    r.append(' ');
11068                }
11069                r.append(a.info.name);
11070            }
11071        }
11072        if (r != null) {
11073            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11074        }
11075
11076        r = null;
11077        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11078            // Only system apps can hold shared libraries.
11079            if (pkg.libraryNames != null) {
11080                for (i = 0; i < pkg.libraryNames.size(); i++) {
11081                    String name = pkg.libraryNames.get(i);
11082                    if (removeSharedLibraryLPw(name, 0)) {
11083                        if (DEBUG_REMOVE && chatty) {
11084                            if (r == null) {
11085                                r = new StringBuilder(256);
11086                            } else {
11087                                r.append(' ');
11088                            }
11089                            r.append(name);
11090                        }
11091                    }
11092                }
11093            }
11094        }
11095
11096        r = null;
11097
11098        // Any package can hold static shared libraries.
11099        if (pkg.staticSharedLibName != null) {
11100            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11101                if (DEBUG_REMOVE && chatty) {
11102                    if (r == null) {
11103                        r = new StringBuilder(256);
11104                    } else {
11105                        r.append(' ');
11106                    }
11107                    r.append(pkg.staticSharedLibName);
11108                }
11109            }
11110        }
11111
11112        if (r != null) {
11113            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11114        }
11115    }
11116
11117    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11118        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11119            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11120                return true;
11121            }
11122        }
11123        return false;
11124    }
11125
11126    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11127    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11128    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11129
11130    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11131        // Update the parent permissions
11132        updatePermissionsLPw(pkg.packageName, pkg, flags);
11133        // Update the child permissions
11134        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11135        for (int i = 0; i < childCount; i++) {
11136            PackageParser.Package childPkg = pkg.childPackages.get(i);
11137            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11138        }
11139    }
11140
11141    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11142            int flags) {
11143        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11144        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11145    }
11146
11147    private void updatePermissionsLPw(String changingPkg,
11148            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11149        // Make sure there are no dangling permission trees.
11150        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11151        while (it.hasNext()) {
11152            final BasePermission bp = it.next();
11153            if (bp.packageSetting == null) {
11154                // We may not yet have parsed the package, so just see if
11155                // we still know about its settings.
11156                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11157            }
11158            if (bp.packageSetting == null) {
11159                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11160                        + " from package " + bp.sourcePackage);
11161                it.remove();
11162            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11163                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11164                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11165                            + " from package " + bp.sourcePackage);
11166                    flags |= UPDATE_PERMISSIONS_ALL;
11167                    it.remove();
11168                }
11169            }
11170        }
11171
11172        // Make sure all dynamic permissions have been assigned to a package,
11173        // and make sure there are no dangling permissions.
11174        it = mSettings.mPermissions.values().iterator();
11175        while (it.hasNext()) {
11176            final BasePermission bp = it.next();
11177            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11178                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11179                        + bp.name + " pkg=" + bp.sourcePackage
11180                        + " info=" + bp.pendingInfo);
11181                if (bp.packageSetting == null && bp.pendingInfo != null) {
11182                    final BasePermission tree = findPermissionTreeLP(bp.name);
11183                    if (tree != null && tree.perm != null) {
11184                        bp.packageSetting = tree.packageSetting;
11185                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11186                                new PermissionInfo(bp.pendingInfo));
11187                        bp.perm.info.packageName = tree.perm.info.packageName;
11188                        bp.perm.info.name = bp.name;
11189                        bp.uid = tree.uid;
11190                    }
11191                }
11192            }
11193            if (bp.packageSetting == null) {
11194                // We may not yet have parsed the package, so just see if
11195                // we still know about its settings.
11196                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11197            }
11198            if (bp.packageSetting == null) {
11199                Slog.w(TAG, "Removing dangling permission: " + bp.name
11200                        + " from package " + bp.sourcePackage);
11201                it.remove();
11202            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11203                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11204                    Slog.i(TAG, "Removing old permission: " + bp.name
11205                            + " from package " + bp.sourcePackage);
11206                    flags |= UPDATE_PERMISSIONS_ALL;
11207                    it.remove();
11208                }
11209            }
11210        }
11211
11212        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11213        // Now update the permissions for all packages, in particular
11214        // replace the granted permissions of the system packages.
11215        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11216            for (PackageParser.Package pkg : mPackages.values()) {
11217                if (pkg != pkgInfo) {
11218                    // Only replace for packages on requested volume
11219                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11220                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11221                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11222                    grantPermissionsLPw(pkg, replace, changingPkg);
11223                }
11224            }
11225        }
11226
11227        if (pkgInfo != null) {
11228            // Only replace for packages on requested volume
11229            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11230            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11231                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11232            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11233        }
11234        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11235    }
11236
11237    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11238            String packageOfInterest) {
11239        // IMPORTANT: There are two types of permissions: install and runtime.
11240        // Install time permissions are granted when the app is installed to
11241        // all device users and users added in the future. Runtime permissions
11242        // are granted at runtime explicitly to specific users. Normal and signature
11243        // protected permissions are install time permissions. Dangerous permissions
11244        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11245        // otherwise they are runtime permissions. This function does not manage
11246        // runtime permissions except for the case an app targeting Lollipop MR1
11247        // being upgraded to target a newer SDK, in which case dangerous permissions
11248        // are transformed from install time to runtime ones.
11249
11250        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11251        if (ps == null) {
11252            return;
11253        }
11254
11255        PermissionsState permissionsState = ps.getPermissionsState();
11256        PermissionsState origPermissions = permissionsState;
11257
11258        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11259
11260        boolean runtimePermissionsRevoked = false;
11261        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11262
11263        boolean changedInstallPermission = false;
11264
11265        if (replace) {
11266            ps.installPermissionsFixed = false;
11267            if (!ps.isSharedUser()) {
11268                origPermissions = new PermissionsState(permissionsState);
11269                permissionsState.reset();
11270            } else {
11271                // We need to know only about runtime permission changes since the
11272                // calling code always writes the install permissions state but
11273                // the runtime ones are written only if changed. The only cases of
11274                // changed runtime permissions here are promotion of an install to
11275                // runtime and revocation of a runtime from a shared user.
11276                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11277                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11278                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11279                    runtimePermissionsRevoked = true;
11280                }
11281            }
11282        }
11283
11284        permissionsState.setGlobalGids(mGlobalGids);
11285
11286        final int N = pkg.requestedPermissions.size();
11287        for (int i=0; i<N; i++) {
11288            final String name = pkg.requestedPermissions.get(i);
11289            final BasePermission bp = mSettings.mPermissions.get(name);
11290
11291            if (DEBUG_INSTALL) {
11292                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11293            }
11294
11295            if (bp == null || bp.packageSetting == null) {
11296                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11297                    Slog.w(TAG, "Unknown permission " + name
11298                            + " in package " + pkg.packageName);
11299                }
11300                continue;
11301            }
11302
11303
11304            // Limit ephemeral apps to ephemeral allowed permissions.
11305            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11306                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11307                        + pkg.packageName);
11308                continue;
11309            }
11310
11311            final String perm = bp.name;
11312            boolean allowedSig = false;
11313            int grant = GRANT_DENIED;
11314
11315            // Keep track of app op permissions.
11316            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11317                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11318                if (pkgs == null) {
11319                    pkgs = new ArraySet<>();
11320                    mAppOpPermissionPackages.put(bp.name, pkgs);
11321                }
11322                pkgs.add(pkg.packageName);
11323            }
11324
11325            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11326            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11327                    >= Build.VERSION_CODES.M;
11328            switch (level) {
11329                case PermissionInfo.PROTECTION_NORMAL: {
11330                    // For all apps normal permissions are install time ones.
11331                    grant = GRANT_INSTALL;
11332                } break;
11333
11334                case PermissionInfo.PROTECTION_DANGEROUS: {
11335                    // If a permission review is required for legacy apps we represent
11336                    // their permissions as always granted runtime ones since we need
11337                    // to keep the review required permission flag per user while an
11338                    // install permission's state is shared across all users.
11339                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11340                        // For legacy apps dangerous permissions are install time ones.
11341                        grant = GRANT_INSTALL;
11342                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11343                        // For legacy apps that became modern, install becomes runtime.
11344                        grant = GRANT_UPGRADE;
11345                    } else if (mPromoteSystemApps
11346                            && isSystemApp(ps)
11347                            && mExistingSystemPackages.contains(ps.name)) {
11348                        // For legacy system apps, install becomes runtime.
11349                        // We cannot check hasInstallPermission() for system apps since those
11350                        // permissions were granted implicitly and not persisted pre-M.
11351                        grant = GRANT_UPGRADE;
11352                    } else {
11353                        // For modern apps keep runtime permissions unchanged.
11354                        grant = GRANT_RUNTIME;
11355                    }
11356                } break;
11357
11358                case PermissionInfo.PROTECTION_SIGNATURE: {
11359                    // For all apps signature permissions are install time ones.
11360                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11361                    if (allowedSig) {
11362                        grant = GRANT_INSTALL;
11363                    }
11364                } break;
11365            }
11366
11367            if (DEBUG_INSTALL) {
11368                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11369            }
11370
11371            if (grant != GRANT_DENIED) {
11372                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11373                    // If this is an existing, non-system package, then
11374                    // we can't add any new permissions to it.
11375                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11376                        // Except...  if this is a permission that was added
11377                        // to the platform (note: need to only do this when
11378                        // updating the platform).
11379                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11380                            grant = GRANT_DENIED;
11381                        }
11382                    }
11383                }
11384
11385                switch (grant) {
11386                    case GRANT_INSTALL: {
11387                        // Revoke this as runtime permission to handle the case of
11388                        // a runtime permission being downgraded to an install one.
11389                        // Also in permission review mode we keep dangerous permissions
11390                        // for legacy apps
11391                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11392                            if (origPermissions.getRuntimePermissionState(
11393                                    bp.name, userId) != null) {
11394                                // Revoke the runtime permission and clear the flags.
11395                                origPermissions.revokeRuntimePermission(bp, userId);
11396                                origPermissions.updatePermissionFlags(bp, userId,
11397                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11398                                // If we revoked a permission permission, we have to write.
11399                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11400                                        changedRuntimePermissionUserIds, userId);
11401                            }
11402                        }
11403                        // Grant an install permission.
11404                        if (permissionsState.grantInstallPermission(bp) !=
11405                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11406                            changedInstallPermission = true;
11407                        }
11408                    } break;
11409
11410                    case GRANT_RUNTIME: {
11411                        // Grant previously granted runtime permissions.
11412                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11413                            PermissionState permissionState = origPermissions
11414                                    .getRuntimePermissionState(bp.name, userId);
11415                            int flags = permissionState != null
11416                                    ? permissionState.getFlags() : 0;
11417                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11418                                // Don't propagate the permission in a permission review mode if
11419                                // the former was revoked, i.e. marked to not propagate on upgrade.
11420                                // Note that in a permission review mode install permissions are
11421                                // represented as constantly granted runtime ones since we need to
11422                                // keep a per user state associated with the permission. Also the
11423                                // revoke on upgrade flag is no longer applicable and is reset.
11424                                final boolean revokeOnUpgrade = (flags & PackageManager
11425                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11426                                if (revokeOnUpgrade) {
11427                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11428                                    // Since we changed the flags, we have to write.
11429                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11430                                            changedRuntimePermissionUserIds, userId);
11431                                }
11432                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11433                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11434                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11435                                        // If we cannot put the permission as it was,
11436                                        // we have to write.
11437                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11438                                                changedRuntimePermissionUserIds, userId);
11439                                    }
11440                                }
11441
11442                                // If the app supports runtime permissions no need for a review.
11443                                if (mPermissionReviewRequired
11444                                        && appSupportsRuntimePermissions
11445                                        && (flags & PackageManager
11446                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11447                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11448                                    // Since we changed the flags, we have to write.
11449                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11450                                            changedRuntimePermissionUserIds, userId);
11451                                }
11452                            } else if (mPermissionReviewRequired
11453                                    && !appSupportsRuntimePermissions) {
11454                                // For legacy apps that need a permission review, every new
11455                                // runtime permission is granted but it is pending a review.
11456                                // We also need to review only platform defined runtime
11457                                // permissions as these are the only ones the platform knows
11458                                // how to disable the API to simulate revocation as legacy
11459                                // apps don't expect to run with revoked permissions.
11460                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11461                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11462                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11463                                        // We changed the flags, hence have to write.
11464                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11465                                                changedRuntimePermissionUserIds, userId);
11466                                    }
11467                                }
11468                                if (permissionsState.grantRuntimePermission(bp, userId)
11469                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11470                                    // We changed the permission, hence have to write.
11471                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11472                                            changedRuntimePermissionUserIds, userId);
11473                                }
11474                            }
11475                            // Propagate the permission flags.
11476                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11477                        }
11478                    } break;
11479
11480                    case GRANT_UPGRADE: {
11481                        // Grant runtime permissions for a previously held install permission.
11482                        PermissionState permissionState = origPermissions
11483                                .getInstallPermissionState(bp.name);
11484                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11485
11486                        if (origPermissions.revokeInstallPermission(bp)
11487                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11488                            // We will be transferring the permission flags, so clear them.
11489                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11490                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11491                            changedInstallPermission = true;
11492                        }
11493
11494                        // If the permission is not to be promoted to runtime we ignore it and
11495                        // also its other flags as they are not applicable to install permissions.
11496                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11497                            for (int userId : currentUserIds) {
11498                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11499                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11500                                    // Transfer the permission flags.
11501                                    permissionsState.updatePermissionFlags(bp, userId,
11502                                            flags, flags);
11503                                    // If we granted the permission, we have to write.
11504                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11505                                            changedRuntimePermissionUserIds, userId);
11506                                }
11507                            }
11508                        }
11509                    } break;
11510
11511                    default: {
11512                        if (packageOfInterest == null
11513                                || packageOfInterest.equals(pkg.packageName)) {
11514                            Slog.w(TAG, "Not granting permission " + perm
11515                                    + " to package " + pkg.packageName
11516                                    + " because it was previously installed without");
11517                        }
11518                    } break;
11519                }
11520            } else {
11521                if (permissionsState.revokeInstallPermission(bp) !=
11522                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11523                    // Also drop the permission flags.
11524                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11525                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11526                    changedInstallPermission = true;
11527                    Slog.i(TAG, "Un-granting permission " + perm
11528                            + " from package " + pkg.packageName
11529                            + " (protectionLevel=" + bp.protectionLevel
11530                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11531                            + ")");
11532                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11533                    // Don't print warning for app op permissions, since it is fine for them
11534                    // not to be granted, there is a UI for the user to decide.
11535                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11536                        Slog.w(TAG, "Not granting permission " + perm
11537                                + " to package " + pkg.packageName
11538                                + " (protectionLevel=" + bp.protectionLevel
11539                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11540                                + ")");
11541                    }
11542                }
11543            }
11544        }
11545
11546        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11547                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11548            // This is the first that we have heard about this package, so the
11549            // permissions we have now selected are fixed until explicitly
11550            // changed.
11551            ps.installPermissionsFixed = true;
11552        }
11553
11554        // Persist the runtime permissions state for users with changes. If permissions
11555        // were revoked because no app in the shared user declares them we have to
11556        // write synchronously to avoid losing runtime permissions state.
11557        for (int userId : changedRuntimePermissionUserIds) {
11558            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11559        }
11560    }
11561
11562    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11563        boolean allowed = false;
11564        final int NP = PackageParser.NEW_PERMISSIONS.length;
11565        for (int ip=0; ip<NP; ip++) {
11566            final PackageParser.NewPermissionInfo npi
11567                    = PackageParser.NEW_PERMISSIONS[ip];
11568            if (npi.name.equals(perm)
11569                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11570                allowed = true;
11571                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11572                        + pkg.packageName);
11573                break;
11574            }
11575        }
11576        return allowed;
11577    }
11578
11579    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11580            BasePermission bp, PermissionsState origPermissions) {
11581        boolean privilegedPermission = (bp.protectionLevel
11582                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11583        boolean privappPermissionsDisable =
11584                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11585        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11586        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11587        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11588                && !platformPackage && platformPermission) {
11589            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11590                    .getPrivAppPermissions(pkg.packageName);
11591            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11592            if (!whitelisted) {
11593                Slog.w(TAG, "Privileged permission " + perm + " for package "
11594                        + pkg.packageName + " - not in privapp-permissions whitelist");
11595                // Only report violations for apps on system image
11596                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11597                    if (mPrivappPermissionsViolations == null) {
11598                        mPrivappPermissionsViolations = new ArraySet<>();
11599                    }
11600                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11601                }
11602                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11603                    return false;
11604                }
11605            }
11606        }
11607        boolean allowed = (compareSignatures(
11608                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11609                        == PackageManager.SIGNATURE_MATCH)
11610                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11611                        == PackageManager.SIGNATURE_MATCH);
11612        if (!allowed && privilegedPermission) {
11613            if (isSystemApp(pkg)) {
11614                // For updated system applications, a system permission
11615                // is granted only if it had been defined by the original application.
11616                if (pkg.isUpdatedSystemApp()) {
11617                    final PackageSetting sysPs = mSettings
11618                            .getDisabledSystemPkgLPr(pkg.packageName);
11619                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11620                        // If the original was granted this permission, we take
11621                        // that grant decision as read and propagate it to the
11622                        // update.
11623                        if (sysPs.isPrivileged()) {
11624                            allowed = true;
11625                        }
11626                    } else {
11627                        // The system apk may have been updated with an older
11628                        // version of the one on the data partition, but which
11629                        // granted a new system permission that it didn't have
11630                        // before.  In this case we do want to allow the app to
11631                        // now get the new permission if the ancestral apk is
11632                        // privileged to get it.
11633                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11634                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11635                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11636                                    allowed = true;
11637                                    break;
11638                                }
11639                            }
11640                        }
11641                        // Also if a privileged parent package on the system image or any of
11642                        // its children requested a privileged permission, the updated child
11643                        // packages can also get the permission.
11644                        if (pkg.parentPackage != null) {
11645                            final PackageSetting disabledSysParentPs = mSettings
11646                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11647                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11648                                    && disabledSysParentPs.isPrivileged()) {
11649                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11650                                    allowed = true;
11651                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11652                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11653                                    for (int i = 0; i < count; i++) {
11654                                        PackageParser.Package disabledSysChildPkg =
11655                                                disabledSysParentPs.pkg.childPackages.get(i);
11656                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11657                                                perm)) {
11658                                            allowed = true;
11659                                            break;
11660                                        }
11661                                    }
11662                                }
11663                            }
11664                        }
11665                    }
11666                } else {
11667                    allowed = isPrivilegedApp(pkg);
11668                }
11669            }
11670        }
11671        if (!allowed) {
11672            if (!allowed && (bp.protectionLevel
11673                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11674                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11675                // If this was a previously normal/dangerous permission that got moved
11676                // to a system permission as part of the runtime permission redesign, then
11677                // we still want to blindly grant it to old apps.
11678                allowed = true;
11679            }
11680            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11681                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11682                // If this permission is to be granted to the system installer and
11683                // this app is an installer, then it gets the permission.
11684                allowed = true;
11685            }
11686            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11687                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11688                // If this permission is to be granted to the system verifier and
11689                // this app is a verifier, then it gets the permission.
11690                allowed = true;
11691            }
11692            if (!allowed && (bp.protectionLevel
11693                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11694                    && isSystemApp(pkg)) {
11695                // Any pre-installed system app is allowed to get this permission.
11696                allowed = true;
11697            }
11698            if (!allowed && (bp.protectionLevel
11699                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11700                // For development permissions, a development permission
11701                // is granted only if it was already granted.
11702                allowed = origPermissions.hasInstallPermission(perm);
11703            }
11704            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11705                    && pkg.packageName.equals(mSetupWizardPackage)) {
11706                // If this permission is to be granted to the system setup wizard and
11707                // this app is a setup wizard, then it gets the permission.
11708                allowed = true;
11709            }
11710        }
11711        return allowed;
11712    }
11713
11714    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11715        final int permCount = pkg.requestedPermissions.size();
11716        for (int j = 0; j < permCount; j++) {
11717            String requestedPermission = pkg.requestedPermissions.get(j);
11718            if (permission.equals(requestedPermission)) {
11719                return true;
11720            }
11721        }
11722        return false;
11723    }
11724
11725    final class ActivityIntentResolver
11726            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11727        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11728                boolean defaultOnly, int userId) {
11729            if (!sUserManager.exists(userId)) return null;
11730            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11731            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11732        }
11733
11734        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11735                int userId) {
11736            if (!sUserManager.exists(userId)) return null;
11737            mFlags = flags;
11738            return super.queryIntent(intent, resolvedType,
11739                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11740                    userId);
11741        }
11742
11743        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11744                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11745            if (!sUserManager.exists(userId)) return null;
11746            if (packageActivities == null) {
11747                return null;
11748            }
11749            mFlags = flags;
11750            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11751            final int N = packageActivities.size();
11752            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11753                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11754
11755            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11756            for (int i = 0; i < N; ++i) {
11757                intentFilters = packageActivities.get(i).intents;
11758                if (intentFilters != null && intentFilters.size() > 0) {
11759                    PackageParser.ActivityIntentInfo[] array =
11760                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11761                    intentFilters.toArray(array);
11762                    listCut.add(array);
11763                }
11764            }
11765            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11766        }
11767
11768        /**
11769         * Finds a privileged activity that matches the specified activity names.
11770         */
11771        private PackageParser.Activity findMatchingActivity(
11772                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11773            for (PackageParser.Activity sysActivity : activityList) {
11774                if (sysActivity.info.name.equals(activityInfo.name)) {
11775                    return sysActivity;
11776                }
11777                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11778                    return sysActivity;
11779                }
11780                if (sysActivity.info.targetActivity != null) {
11781                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11782                        return sysActivity;
11783                    }
11784                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11785                        return sysActivity;
11786                    }
11787                }
11788            }
11789            return null;
11790        }
11791
11792        public class IterGenerator<E> {
11793            public Iterator<E> generate(ActivityIntentInfo info) {
11794                return null;
11795            }
11796        }
11797
11798        public class ActionIterGenerator extends IterGenerator<String> {
11799            @Override
11800            public Iterator<String> generate(ActivityIntentInfo info) {
11801                return info.actionsIterator();
11802            }
11803        }
11804
11805        public class CategoriesIterGenerator extends IterGenerator<String> {
11806            @Override
11807            public Iterator<String> generate(ActivityIntentInfo info) {
11808                return info.categoriesIterator();
11809            }
11810        }
11811
11812        public class SchemesIterGenerator extends IterGenerator<String> {
11813            @Override
11814            public Iterator<String> generate(ActivityIntentInfo info) {
11815                return info.schemesIterator();
11816            }
11817        }
11818
11819        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11820            @Override
11821            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11822                return info.authoritiesIterator();
11823            }
11824        }
11825
11826        /**
11827         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11828         * MODIFIED. Do not pass in a list that should not be changed.
11829         */
11830        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11831                IterGenerator<T> generator, Iterator<T> searchIterator) {
11832            // loop through the set of actions; every one must be found in the intent filter
11833            while (searchIterator.hasNext()) {
11834                // we must have at least one filter in the list to consider a match
11835                if (intentList.size() == 0) {
11836                    break;
11837                }
11838
11839                final T searchAction = searchIterator.next();
11840
11841                // loop through the set of intent filters
11842                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11843                while (intentIter.hasNext()) {
11844                    final ActivityIntentInfo intentInfo = intentIter.next();
11845                    boolean selectionFound = false;
11846
11847                    // loop through the intent filter's selection criteria; at least one
11848                    // of them must match the searched criteria
11849                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11850                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11851                        final T intentSelection = intentSelectionIter.next();
11852                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11853                            selectionFound = true;
11854                            break;
11855                        }
11856                    }
11857
11858                    // the selection criteria wasn't found in this filter's set; this filter
11859                    // is not a potential match
11860                    if (!selectionFound) {
11861                        intentIter.remove();
11862                    }
11863                }
11864            }
11865        }
11866
11867        private boolean isProtectedAction(ActivityIntentInfo filter) {
11868            final Iterator<String> actionsIter = filter.actionsIterator();
11869            while (actionsIter != null && actionsIter.hasNext()) {
11870                final String filterAction = actionsIter.next();
11871                if (PROTECTED_ACTIONS.contains(filterAction)) {
11872                    return true;
11873                }
11874            }
11875            return false;
11876        }
11877
11878        /**
11879         * Adjusts the priority of the given intent filter according to policy.
11880         * <p>
11881         * <ul>
11882         * <li>The priority for non privileged applications is capped to '0'</li>
11883         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11884         * <li>The priority for unbundled updates to privileged applications is capped to the
11885         *      priority defined on the system partition</li>
11886         * </ul>
11887         * <p>
11888         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11889         * allowed to obtain any priority on any action.
11890         */
11891        private void adjustPriority(
11892                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11893            // nothing to do; priority is fine as-is
11894            if (intent.getPriority() <= 0) {
11895                return;
11896            }
11897
11898            final ActivityInfo activityInfo = intent.activity.info;
11899            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11900
11901            final boolean privilegedApp =
11902                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11903            if (!privilegedApp) {
11904                // non-privileged applications can never define a priority >0
11905                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11906                        + " package: " + applicationInfo.packageName
11907                        + " activity: " + intent.activity.className
11908                        + " origPrio: " + intent.getPriority());
11909                intent.setPriority(0);
11910                return;
11911            }
11912
11913            if (systemActivities == null) {
11914                // the system package is not disabled; we're parsing the system partition
11915                if (isProtectedAction(intent)) {
11916                    if (mDeferProtectedFilters) {
11917                        // We can't deal with these just yet. No component should ever obtain a
11918                        // >0 priority for a protected actions, with ONE exception -- the setup
11919                        // wizard. The setup wizard, however, cannot be known until we're able to
11920                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11921                        // until all intent filters have been processed. Chicken, meet egg.
11922                        // Let the filter temporarily have a high priority and rectify the
11923                        // priorities after all system packages have been scanned.
11924                        mProtectedFilters.add(intent);
11925                        if (DEBUG_FILTERS) {
11926                            Slog.i(TAG, "Protected action; save for later;"
11927                                    + " package: " + applicationInfo.packageName
11928                                    + " activity: " + intent.activity.className
11929                                    + " origPrio: " + intent.getPriority());
11930                        }
11931                        return;
11932                    } else {
11933                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11934                            Slog.i(TAG, "No setup wizard;"
11935                                + " All protected intents capped to priority 0");
11936                        }
11937                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11938                            if (DEBUG_FILTERS) {
11939                                Slog.i(TAG, "Found setup wizard;"
11940                                    + " allow priority " + intent.getPriority() + ";"
11941                                    + " package: " + intent.activity.info.packageName
11942                                    + " activity: " + intent.activity.className
11943                                    + " priority: " + intent.getPriority());
11944                            }
11945                            // setup wizard gets whatever it wants
11946                            return;
11947                        }
11948                        Slog.w(TAG, "Protected action; cap priority to 0;"
11949                                + " package: " + intent.activity.info.packageName
11950                                + " activity: " + intent.activity.className
11951                                + " origPrio: " + intent.getPriority());
11952                        intent.setPriority(0);
11953                        return;
11954                    }
11955                }
11956                // privileged apps on the system image get whatever priority they request
11957                return;
11958            }
11959
11960            // privileged app unbundled update ... try to find the same activity
11961            final PackageParser.Activity foundActivity =
11962                    findMatchingActivity(systemActivities, activityInfo);
11963            if (foundActivity == null) {
11964                // this is a new activity; it cannot obtain >0 priority
11965                if (DEBUG_FILTERS) {
11966                    Slog.i(TAG, "New activity; cap priority to 0;"
11967                            + " package: " + applicationInfo.packageName
11968                            + " activity: " + intent.activity.className
11969                            + " origPrio: " + intent.getPriority());
11970                }
11971                intent.setPriority(0);
11972                return;
11973            }
11974
11975            // found activity, now check for filter equivalence
11976
11977            // a shallow copy is enough; we modify the list, not its contents
11978            final List<ActivityIntentInfo> intentListCopy =
11979                    new ArrayList<>(foundActivity.intents);
11980            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11981
11982            // find matching action subsets
11983            final Iterator<String> actionsIterator = intent.actionsIterator();
11984            if (actionsIterator != null) {
11985                getIntentListSubset(
11986                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11987                if (intentListCopy.size() == 0) {
11988                    // no more intents to match; we're not equivalent
11989                    if (DEBUG_FILTERS) {
11990                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11991                                + " package: " + applicationInfo.packageName
11992                                + " activity: " + intent.activity.className
11993                                + " origPrio: " + intent.getPriority());
11994                    }
11995                    intent.setPriority(0);
11996                    return;
11997                }
11998            }
11999
12000            // find matching category subsets
12001            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12002            if (categoriesIterator != null) {
12003                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12004                        categoriesIterator);
12005                if (intentListCopy.size() == 0) {
12006                    // no more intents to match; we're not equivalent
12007                    if (DEBUG_FILTERS) {
12008                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12009                                + " package: " + applicationInfo.packageName
12010                                + " activity: " + intent.activity.className
12011                                + " origPrio: " + intent.getPriority());
12012                    }
12013                    intent.setPriority(0);
12014                    return;
12015                }
12016            }
12017
12018            // find matching schemes subsets
12019            final Iterator<String> schemesIterator = intent.schemesIterator();
12020            if (schemesIterator != null) {
12021                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12022                        schemesIterator);
12023                if (intentListCopy.size() == 0) {
12024                    // no more intents to match; we're not equivalent
12025                    if (DEBUG_FILTERS) {
12026                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12027                                + " package: " + applicationInfo.packageName
12028                                + " activity: " + intent.activity.className
12029                                + " origPrio: " + intent.getPriority());
12030                    }
12031                    intent.setPriority(0);
12032                    return;
12033                }
12034            }
12035
12036            // find matching authorities subsets
12037            final Iterator<IntentFilter.AuthorityEntry>
12038                    authoritiesIterator = intent.authoritiesIterator();
12039            if (authoritiesIterator != null) {
12040                getIntentListSubset(intentListCopy,
12041                        new AuthoritiesIterGenerator(),
12042                        authoritiesIterator);
12043                if (intentListCopy.size() == 0) {
12044                    // no more intents to match; we're not equivalent
12045                    if (DEBUG_FILTERS) {
12046                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12047                                + " package: " + applicationInfo.packageName
12048                                + " activity: " + intent.activity.className
12049                                + " origPrio: " + intent.getPriority());
12050                    }
12051                    intent.setPriority(0);
12052                    return;
12053                }
12054            }
12055
12056            // we found matching filter(s); app gets the max priority of all intents
12057            int cappedPriority = 0;
12058            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12059                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12060            }
12061            if (intent.getPriority() > cappedPriority) {
12062                if (DEBUG_FILTERS) {
12063                    Slog.i(TAG, "Found matching filter(s);"
12064                            + " cap priority to " + cappedPriority + ";"
12065                            + " package: " + applicationInfo.packageName
12066                            + " activity: " + intent.activity.className
12067                            + " origPrio: " + intent.getPriority());
12068                }
12069                intent.setPriority(cappedPriority);
12070                return;
12071            }
12072            // all this for nothing; the requested priority was <= what was on the system
12073        }
12074
12075        public final void addActivity(PackageParser.Activity a, String type) {
12076            mActivities.put(a.getComponentName(), a);
12077            if (DEBUG_SHOW_INFO)
12078                Log.v(
12079                TAG, "  " + type + " " +
12080                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12081            if (DEBUG_SHOW_INFO)
12082                Log.v(TAG, "    Class=" + a.info.name);
12083            final int NI = a.intents.size();
12084            for (int j=0; j<NI; j++) {
12085                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12086                if ("activity".equals(type)) {
12087                    final PackageSetting ps =
12088                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12089                    final List<PackageParser.Activity> systemActivities =
12090                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12091                    adjustPriority(systemActivities, intent);
12092                }
12093                if (DEBUG_SHOW_INFO) {
12094                    Log.v(TAG, "    IntentFilter:");
12095                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12096                }
12097                if (!intent.debugCheck()) {
12098                    Log.w(TAG, "==> For Activity " + a.info.name);
12099                }
12100                addFilter(intent);
12101            }
12102        }
12103
12104        public final void removeActivity(PackageParser.Activity a, String type) {
12105            mActivities.remove(a.getComponentName());
12106            if (DEBUG_SHOW_INFO) {
12107                Log.v(TAG, "  " + type + " "
12108                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12109                                : a.info.name) + ":");
12110                Log.v(TAG, "    Class=" + a.info.name);
12111            }
12112            final int NI = a.intents.size();
12113            for (int j=0; j<NI; j++) {
12114                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12115                if (DEBUG_SHOW_INFO) {
12116                    Log.v(TAG, "    IntentFilter:");
12117                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12118                }
12119                removeFilter(intent);
12120            }
12121        }
12122
12123        @Override
12124        protected boolean allowFilterResult(
12125                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12126            ActivityInfo filterAi = filter.activity.info;
12127            for (int i=dest.size()-1; i>=0; i--) {
12128                ActivityInfo destAi = dest.get(i).activityInfo;
12129                if (destAi.name == filterAi.name
12130                        && destAi.packageName == filterAi.packageName) {
12131                    return false;
12132                }
12133            }
12134            return true;
12135        }
12136
12137        @Override
12138        protected ActivityIntentInfo[] newArray(int size) {
12139            return new ActivityIntentInfo[size];
12140        }
12141
12142        @Override
12143        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12144            if (!sUserManager.exists(userId)) return true;
12145            PackageParser.Package p = filter.activity.owner;
12146            if (p != null) {
12147                PackageSetting ps = (PackageSetting)p.mExtras;
12148                if (ps != null) {
12149                    // System apps are never considered stopped for purposes of
12150                    // filtering, because there may be no way for the user to
12151                    // actually re-launch them.
12152                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12153                            && ps.getStopped(userId);
12154                }
12155            }
12156            return false;
12157        }
12158
12159        @Override
12160        protected boolean isPackageForFilter(String packageName,
12161                PackageParser.ActivityIntentInfo info) {
12162            return packageName.equals(info.activity.owner.packageName);
12163        }
12164
12165        @Override
12166        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12167                int match, int userId) {
12168            if (!sUserManager.exists(userId)) return null;
12169            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12170                return null;
12171            }
12172            final PackageParser.Activity activity = info.activity;
12173            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12174            if (ps == null) {
12175                return null;
12176            }
12177            final PackageUserState userState = ps.readUserState(userId);
12178            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12179                    userState, userId);
12180            if (ai == null) {
12181                return null;
12182            }
12183            final boolean matchVisibleToInstantApp =
12184                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12185            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12186            // throw out filters that aren't visible to ephemeral apps
12187            if (matchVisibleToInstantApp
12188                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12189                return null;
12190            }
12191            // throw out ephemeral filters if we're not explicitly requesting them
12192            if (!isInstantApp && userState.instantApp) {
12193                return null;
12194            }
12195            // throw out instant app filters if updates are available; will trigger
12196            // instant app resolution
12197            if (userState.instantApp && ps.isUpdateAvailable()) {
12198                return null;
12199            }
12200            final ResolveInfo res = new ResolveInfo();
12201            res.activityInfo = ai;
12202            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12203                res.filter = info;
12204            }
12205            if (info != null) {
12206                res.handleAllWebDataURI = info.handleAllWebDataURI();
12207            }
12208            res.priority = info.getPriority();
12209            res.preferredOrder = activity.owner.mPreferredOrder;
12210            //System.out.println("Result: " + res.activityInfo.className +
12211            //                   " = " + res.priority);
12212            res.match = match;
12213            res.isDefault = info.hasDefault;
12214            res.labelRes = info.labelRes;
12215            res.nonLocalizedLabel = info.nonLocalizedLabel;
12216            if (userNeedsBadging(userId)) {
12217                res.noResourceId = true;
12218            } else {
12219                res.icon = info.icon;
12220            }
12221            res.iconResourceId = info.icon;
12222            res.system = res.activityInfo.applicationInfo.isSystemApp();
12223            res.instantAppAvailable = userState.instantApp;
12224            return res;
12225        }
12226
12227        @Override
12228        protected void sortResults(List<ResolveInfo> results) {
12229            Collections.sort(results, mResolvePrioritySorter);
12230        }
12231
12232        @Override
12233        protected void dumpFilter(PrintWriter out, String prefix,
12234                PackageParser.ActivityIntentInfo filter) {
12235            out.print(prefix); out.print(
12236                    Integer.toHexString(System.identityHashCode(filter.activity)));
12237                    out.print(' ');
12238                    filter.activity.printComponentShortName(out);
12239                    out.print(" filter ");
12240                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12241        }
12242
12243        @Override
12244        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12245            return filter.activity;
12246        }
12247
12248        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12249            PackageParser.Activity activity = (PackageParser.Activity)label;
12250            out.print(prefix); out.print(
12251                    Integer.toHexString(System.identityHashCode(activity)));
12252                    out.print(' ');
12253                    activity.printComponentShortName(out);
12254            if (count > 1) {
12255                out.print(" ("); out.print(count); out.print(" filters)");
12256            }
12257            out.println();
12258        }
12259
12260        // Keys are String (activity class name), values are Activity.
12261        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12262                = new ArrayMap<ComponentName, PackageParser.Activity>();
12263        private int mFlags;
12264    }
12265
12266    private final class ServiceIntentResolver
12267            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12268        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12269                boolean defaultOnly, int userId) {
12270            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12271            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12272        }
12273
12274        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12275                int userId) {
12276            if (!sUserManager.exists(userId)) return null;
12277            mFlags = flags;
12278            return super.queryIntent(intent, resolvedType,
12279                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12280                    userId);
12281        }
12282
12283        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12284                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12285            if (!sUserManager.exists(userId)) return null;
12286            if (packageServices == null) {
12287                return null;
12288            }
12289            mFlags = flags;
12290            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12291            final int N = packageServices.size();
12292            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12293                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12294
12295            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12296            for (int i = 0; i < N; ++i) {
12297                intentFilters = packageServices.get(i).intents;
12298                if (intentFilters != null && intentFilters.size() > 0) {
12299                    PackageParser.ServiceIntentInfo[] array =
12300                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12301                    intentFilters.toArray(array);
12302                    listCut.add(array);
12303                }
12304            }
12305            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12306        }
12307
12308        public final void addService(PackageParser.Service s) {
12309            mServices.put(s.getComponentName(), s);
12310            if (DEBUG_SHOW_INFO) {
12311                Log.v(TAG, "  "
12312                        + (s.info.nonLocalizedLabel != null
12313                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12314                Log.v(TAG, "    Class=" + s.info.name);
12315            }
12316            final int NI = s.intents.size();
12317            int j;
12318            for (j=0; j<NI; j++) {
12319                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12320                if (DEBUG_SHOW_INFO) {
12321                    Log.v(TAG, "    IntentFilter:");
12322                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12323                }
12324                if (!intent.debugCheck()) {
12325                    Log.w(TAG, "==> For Service " + s.info.name);
12326                }
12327                addFilter(intent);
12328            }
12329        }
12330
12331        public final void removeService(PackageParser.Service s) {
12332            mServices.remove(s.getComponentName());
12333            if (DEBUG_SHOW_INFO) {
12334                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12335                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12336                Log.v(TAG, "    Class=" + s.info.name);
12337            }
12338            final int NI = s.intents.size();
12339            int j;
12340            for (j=0; j<NI; j++) {
12341                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12342                if (DEBUG_SHOW_INFO) {
12343                    Log.v(TAG, "    IntentFilter:");
12344                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12345                }
12346                removeFilter(intent);
12347            }
12348        }
12349
12350        @Override
12351        protected boolean allowFilterResult(
12352                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12353            ServiceInfo filterSi = filter.service.info;
12354            for (int i=dest.size()-1; i>=0; i--) {
12355                ServiceInfo destAi = dest.get(i).serviceInfo;
12356                if (destAi.name == filterSi.name
12357                        && destAi.packageName == filterSi.packageName) {
12358                    return false;
12359                }
12360            }
12361            return true;
12362        }
12363
12364        @Override
12365        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12366            return new PackageParser.ServiceIntentInfo[size];
12367        }
12368
12369        @Override
12370        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12371            if (!sUserManager.exists(userId)) return true;
12372            PackageParser.Package p = filter.service.owner;
12373            if (p != null) {
12374                PackageSetting ps = (PackageSetting)p.mExtras;
12375                if (ps != null) {
12376                    // System apps are never considered stopped for purposes of
12377                    // filtering, because there may be no way for the user to
12378                    // actually re-launch them.
12379                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12380                            && ps.getStopped(userId);
12381                }
12382            }
12383            return false;
12384        }
12385
12386        @Override
12387        protected boolean isPackageForFilter(String packageName,
12388                PackageParser.ServiceIntentInfo info) {
12389            return packageName.equals(info.service.owner.packageName);
12390        }
12391
12392        @Override
12393        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12394                int match, int userId) {
12395            if (!sUserManager.exists(userId)) return null;
12396            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12397            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12398                return null;
12399            }
12400            final PackageParser.Service service = info.service;
12401            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12402            if (ps == null) {
12403                return null;
12404            }
12405            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12406                    ps.readUserState(userId), userId);
12407            if (si == null) {
12408                return null;
12409            }
12410            final ResolveInfo res = new ResolveInfo();
12411            res.serviceInfo = si;
12412            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12413                res.filter = filter;
12414            }
12415            res.priority = info.getPriority();
12416            res.preferredOrder = service.owner.mPreferredOrder;
12417            res.match = match;
12418            res.isDefault = info.hasDefault;
12419            res.labelRes = info.labelRes;
12420            res.nonLocalizedLabel = info.nonLocalizedLabel;
12421            res.icon = info.icon;
12422            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12423            return res;
12424        }
12425
12426        @Override
12427        protected void sortResults(List<ResolveInfo> results) {
12428            Collections.sort(results, mResolvePrioritySorter);
12429        }
12430
12431        @Override
12432        protected void dumpFilter(PrintWriter out, String prefix,
12433                PackageParser.ServiceIntentInfo filter) {
12434            out.print(prefix); out.print(
12435                    Integer.toHexString(System.identityHashCode(filter.service)));
12436                    out.print(' ');
12437                    filter.service.printComponentShortName(out);
12438                    out.print(" filter ");
12439                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12440        }
12441
12442        @Override
12443        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12444            return filter.service;
12445        }
12446
12447        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12448            PackageParser.Service service = (PackageParser.Service)label;
12449            out.print(prefix); out.print(
12450                    Integer.toHexString(System.identityHashCode(service)));
12451                    out.print(' ');
12452                    service.printComponentShortName(out);
12453            if (count > 1) {
12454                out.print(" ("); out.print(count); out.print(" filters)");
12455            }
12456            out.println();
12457        }
12458
12459//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12460//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12461//            final List<ResolveInfo> retList = Lists.newArrayList();
12462//            while (i.hasNext()) {
12463//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12464//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12465//                    retList.add(resolveInfo);
12466//                }
12467//            }
12468//            return retList;
12469//        }
12470
12471        // Keys are String (activity class name), values are Activity.
12472        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12473                = new ArrayMap<ComponentName, PackageParser.Service>();
12474        private int mFlags;
12475    }
12476
12477    private final class ProviderIntentResolver
12478            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12479        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12480                boolean defaultOnly, int userId) {
12481            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12482            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12483        }
12484
12485        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12486                int userId) {
12487            if (!sUserManager.exists(userId))
12488                return null;
12489            mFlags = flags;
12490            return super.queryIntent(intent, resolvedType,
12491                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12492                    userId);
12493        }
12494
12495        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12496                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12497            if (!sUserManager.exists(userId))
12498                return null;
12499            if (packageProviders == null) {
12500                return null;
12501            }
12502            mFlags = flags;
12503            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12504            final int N = packageProviders.size();
12505            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12506                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12507
12508            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12509            for (int i = 0; i < N; ++i) {
12510                intentFilters = packageProviders.get(i).intents;
12511                if (intentFilters != null && intentFilters.size() > 0) {
12512                    PackageParser.ProviderIntentInfo[] array =
12513                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12514                    intentFilters.toArray(array);
12515                    listCut.add(array);
12516                }
12517            }
12518            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12519        }
12520
12521        public final void addProvider(PackageParser.Provider p) {
12522            if (mProviders.containsKey(p.getComponentName())) {
12523                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12524                return;
12525            }
12526
12527            mProviders.put(p.getComponentName(), p);
12528            if (DEBUG_SHOW_INFO) {
12529                Log.v(TAG, "  "
12530                        + (p.info.nonLocalizedLabel != null
12531                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12532                Log.v(TAG, "    Class=" + p.info.name);
12533            }
12534            final int NI = p.intents.size();
12535            int j;
12536            for (j = 0; j < NI; j++) {
12537                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12538                if (DEBUG_SHOW_INFO) {
12539                    Log.v(TAG, "    IntentFilter:");
12540                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12541                }
12542                if (!intent.debugCheck()) {
12543                    Log.w(TAG, "==> For Provider " + p.info.name);
12544                }
12545                addFilter(intent);
12546            }
12547        }
12548
12549        public final void removeProvider(PackageParser.Provider p) {
12550            mProviders.remove(p.getComponentName());
12551            if (DEBUG_SHOW_INFO) {
12552                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12553                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12554                Log.v(TAG, "    Class=" + p.info.name);
12555            }
12556            final int NI = p.intents.size();
12557            int j;
12558            for (j = 0; j < NI; j++) {
12559                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12560                if (DEBUG_SHOW_INFO) {
12561                    Log.v(TAG, "    IntentFilter:");
12562                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12563                }
12564                removeFilter(intent);
12565            }
12566        }
12567
12568        @Override
12569        protected boolean allowFilterResult(
12570                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12571            ProviderInfo filterPi = filter.provider.info;
12572            for (int i = dest.size() - 1; i >= 0; i--) {
12573                ProviderInfo destPi = dest.get(i).providerInfo;
12574                if (destPi.name == filterPi.name
12575                        && destPi.packageName == filterPi.packageName) {
12576                    return false;
12577                }
12578            }
12579            return true;
12580        }
12581
12582        @Override
12583        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12584            return new PackageParser.ProviderIntentInfo[size];
12585        }
12586
12587        @Override
12588        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12589            if (!sUserManager.exists(userId))
12590                return true;
12591            PackageParser.Package p = filter.provider.owner;
12592            if (p != null) {
12593                PackageSetting ps = (PackageSetting) p.mExtras;
12594                if (ps != null) {
12595                    // System apps are never considered stopped for purposes of
12596                    // filtering, because there may be no way for the user to
12597                    // actually re-launch them.
12598                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12599                            && ps.getStopped(userId);
12600                }
12601            }
12602            return false;
12603        }
12604
12605        @Override
12606        protected boolean isPackageForFilter(String packageName,
12607                PackageParser.ProviderIntentInfo info) {
12608            return packageName.equals(info.provider.owner.packageName);
12609        }
12610
12611        @Override
12612        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12613                int match, int userId) {
12614            if (!sUserManager.exists(userId))
12615                return null;
12616            final PackageParser.ProviderIntentInfo info = filter;
12617            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12618                return null;
12619            }
12620            final PackageParser.Provider provider = info.provider;
12621            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12622            if (ps == null) {
12623                return null;
12624            }
12625            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12626                    ps.readUserState(userId), userId);
12627            if (pi == null) {
12628                return null;
12629            }
12630            final ResolveInfo res = new ResolveInfo();
12631            res.providerInfo = pi;
12632            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12633                res.filter = filter;
12634            }
12635            res.priority = info.getPriority();
12636            res.preferredOrder = provider.owner.mPreferredOrder;
12637            res.match = match;
12638            res.isDefault = info.hasDefault;
12639            res.labelRes = info.labelRes;
12640            res.nonLocalizedLabel = info.nonLocalizedLabel;
12641            res.icon = info.icon;
12642            res.system = res.providerInfo.applicationInfo.isSystemApp();
12643            return res;
12644        }
12645
12646        @Override
12647        protected void sortResults(List<ResolveInfo> results) {
12648            Collections.sort(results, mResolvePrioritySorter);
12649        }
12650
12651        @Override
12652        protected void dumpFilter(PrintWriter out, String prefix,
12653                PackageParser.ProviderIntentInfo filter) {
12654            out.print(prefix);
12655            out.print(
12656                    Integer.toHexString(System.identityHashCode(filter.provider)));
12657            out.print(' ');
12658            filter.provider.printComponentShortName(out);
12659            out.print(" filter ");
12660            out.println(Integer.toHexString(System.identityHashCode(filter)));
12661        }
12662
12663        @Override
12664        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12665            return filter.provider;
12666        }
12667
12668        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12669            PackageParser.Provider provider = (PackageParser.Provider)label;
12670            out.print(prefix); out.print(
12671                    Integer.toHexString(System.identityHashCode(provider)));
12672                    out.print(' ');
12673                    provider.printComponentShortName(out);
12674            if (count > 1) {
12675                out.print(" ("); out.print(count); out.print(" filters)");
12676            }
12677            out.println();
12678        }
12679
12680        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12681                = new ArrayMap<ComponentName, PackageParser.Provider>();
12682        private int mFlags;
12683    }
12684
12685    static final class EphemeralIntentResolver
12686            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12687        /**
12688         * The result that has the highest defined order. Ordering applies on a
12689         * per-package basis. Mapping is from package name to Pair of order and
12690         * EphemeralResolveInfo.
12691         * <p>
12692         * NOTE: This is implemented as a field variable for convenience and efficiency.
12693         * By having a field variable, we're able to track filter ordering as soon as
12694         * a non-zero order is defined. Otherwise, multiple loops across the result set
12695         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12696         * this needs to be contained entirely within {@link #filterResults}.
12697         */
12698        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12699
12700        @Override
12701        protected AuxiliaryResolveInfo[] newArray(int size) {
12702            return new AuxiliaryResolveInfo[size];
12703        }
12704
12705        @Override
12706        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12707            return true;
12708        }
12709
12710        @Override
12711        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12712                int userId) {
12713            if (!sUserManager.exists(userId)) {
12714                return null;
12715            }
12716            final String packageName = responseObj.resolveInfo.getPackageName();
12717            final Integer order = responseObj.getOrder();
12718            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12719                    mOrderResult.get(packageName);
12720            // ordering is enabled and this item's order isn't high enough
12721            if (lastOrderResult != null && lastOrderResult.first >= order) {
12722                return null;
12723            }
12724            final InstantAppResolveInfo res = responseObj.resolveInfo;
12725            if (order > 0) {
12726                // non-zero order, enable ordering
12727                mOrderResult.put(packageName, new Pair<>(order, res));
12728            }
12729            return responseObj;
12730        }
12731
12732        @Override
12733        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12734            // only do work if ordering is enabled [most of the time it won't be]
12735            if (mOrderResult.size() == 0) {
12736                return;
12737            }
12738            int resultSize = results.size();
12739            for (int i = 0; i < resultSize; i++) {
12740                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12741                final String packageName = info.getPackageName();
12742                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12743                if (savedInfo == null) {
12744                    // package doesn't having ordering
12745                    continue;
12746                }
12747                if (savedInfo.second == info) {
12748                    // circled back to the highest ordered item; remove from order list
12749                    mOrderResult.remove(savedInfo);
12750                    if (mOrderResult.size() == 0) {
12751                        // no more ordered items
12752                        break;
12753                    }
12754                    continue;
12755                }
12756                // item has a worse order, remove it from the result list
12757                results.remove(i);
12758                resultSize--;
12759                i--;
12760            }
12761        }
12762    }
12763
12764    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12765            new Comparator<ResolveInfo>() {
12766        public int compare(ResolveInfo r1, ResolveInfo r2) {
12767            int v1 = r1.priority;
12768            int v2 = r2.priority;
12769            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12770            if (v1 != v2) {
12771                return (v1 > v2) ? -1 : 1;
12772            }
12773            v1 = r1.preferredOrder;
12774            v2 = r2.preferredOrder;
12775            if (v1 != v2) {
12776                return (v1 > v2) ? -1 : 1;
12777            }
12778            if (r1.isDefault != r2.isDefault) {
12779                return r1.isDefault ? -1 : 1;
12780            }
12781            v1 = r1.match;
12782            v2 = r2.match;
12783            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12784            if (v1 != v2) {
12785                return (v1 > v2) ? -1 : 1;
12786            }
12787            if (r1.system != r2.system) {
12788                return r1.system ? -1 : 1;
12789            }
12790            if (r1.activityInfo != null) {
12791                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12792            }
12793            if (r1.serviceInfo != null) {
12794                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12795            }
12796            if (r1.providerInfo != null) {
12797                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12798            }
12799            return 0;
12800        }
12801    };
12802
12803    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12804            new Comparator<ProviderInfo>() {
12805        public int compare(ProviderInfo p1, ProviderInfo p2) {
12806            final int v1 = p1.initOrder;
12807            final int v2 = p2.initOrder;
12808            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12809        }
12810    };
12811
12812    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12813            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12814            final int[] userIds) {
12815        mHandler.post(new Runnable() {
12816            @Override
12817            public void run() {
12818                try {
12819                    final IActivityManager am = ActivityManager.getService();
12820                    if (am == null) return;
12821                    final int[] resolvedUserIds;
12822                    if (userIds == null) {
12823                        resolvedUserIds = am.getRunningUserIds();
12824                    } else {
12825                        resolvedUserIds = userIds;
12826                    }
12827                    for (int id : resolvedUserIds) {
12828                        final Intent intent = new Intent(action,
12829                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12830                        if (extras != null) {
12831                            intent.putExtras(extras);
12832                        }
12833                        if (targetPkg != null) {
12834                            intent.setPackage(targetPkg);
12835                        }
12836                        // Modify the UID when posting to other users
12837                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12838                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12839                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12840                            intent.putExtra(Intent.EXTRA_UID, uid);
12841                        }
12842                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12843                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12844                        if (DEBUG_BROADCASTS) {
12845                            RuntimeException here = new RuntimeException("here");
12846                            here.fillInStackTrace();
12847                            Slog.d(TAG, "Sending to user " + id + ": "
12848                                    + intent.toShortString(false, true, false, false)
12849                                    + " " + intent.getExtras(), here);
12850                        }
12851                        am.broadcastIntent(null, intent, null, finishedReceiver,
12852                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12853                                null, finishedReceiver != null, false, id);
12854                    }
12855                } catch (RemoteException ex) {
12856                }
12857            }
12858        });
12859    }
12860
12861    /**
12862     * Check if the external storage media is available. This is true if there
12863     * is a mounted external storage medium or if the external storage is
12864     * emulated.
12865     */
12866    private boolean isExternalMediaAvailable() {
12867        return mMediaMounted || Environment.isExternalStorageEmulated();
12868    }
12869
12870    @Override
12871    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12872        // writer
12873        synchronized (mPackages) {
12874            if (!isExternalMediaAvailable()) {
12875                // If the external storage is no longer mounted at this point,
12876                // the caller may not have been able to delete all of this
12877                // packages files and can not delete any more.  Bail.
12878                return null;
12879            }
12880            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12881            if (lastPackage != null) {
12882                pkgs.remove(lastPackage);
12883            }
12884            if (pkgs.size() > 0) {
12885                return pkgs.get(0);
12886            }
12887        }
12888        return null;
12889    }
12890
12891    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12892        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12893                userId, andCode ? 1 : 0, packageName);
12894        if (mSystemReady) {
12895            msg.sendToTarget();
12896        } else {
12897            if (mPostSystemReadyMessages == null) {
12898                mPostSystemReadyMessages = new ArrayList<>();
12899            }
12900            mPostSystemReadyMessages.add(msg);
12901        }
12902    }
12903
12904    void startCleaningPackages() {
12905        // reader
12906        if (!isExternalMediaAvailable()) {
12907            return;
12908        }
12909        synchronized (mPackages) {
12910            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12911                return;
12912            }
12913        }
12914        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12915        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12916        IActivityManager am = ActivityManager.getService();
12917        if (am != null) {
12918            try {
12919                getDeviceIdleController().addPowerSaveTempWhitelistApp(Process.SYSTEM_UID,
12920                        DEFAULT_CONTAINER_PACKAGE, DEFAULT_CONTAINER_WHITELIST_DURATION,
12921                        UserHandle.USER_SYSTEM, false, "cleaning packages");
12922                am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(),
12923                        UserHandle.USER_SYSTEM);
12924            } catch (RemoteException e) {
12925            }
12926        }
12927    }
12928
12929    @Override
12930    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12931            int installFlags, String installerPackageName, int userId) {
12932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12933
12934        final int callingUid = Binder.getCallingUid();
12935        enforceCrossUserPermission(callingUid, userId,
12936                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12937
12938        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12939            try {
12940                if (observer != null) {
12941                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12942                }
12943            } catch (RemoteException re) {
12944            }
12945            return;
12946        }
12947
12948        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12949            installFlags |= PackageManager.INSTALL_FROM_ADB;
12950
12951        } else {
12952            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12953            // about installerPackageName.
12954
12955            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12956            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12957        }
12958
12959        UserHandle user;
12960        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12961            user = UserHandle.ALL;
12962        } else {
12963            user = new UserHandle(userId);
12964        }
12965
12966        // Only system components can circumvent runtime permissions when installing.
12967        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12968                && mContext.checkCallingOrSelfPermission(Manifest.permission
12969                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12970            throw new SecurityException("You need the "
12971                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12972                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12973        }
12974
12975        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12976                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12977            throw new IllegalArgumentException(
12978                    "New installs into ASEC containers no longer supported");
12979        }
12980
12981        final File originFile = new File(originPath);
12982        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12983
12984        final Message msg = mHandler.obtainMessage(INIT_COPY);
12985        final VerificationInfo verificationInfo = new VerificationInfo(
12986                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12987        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12988                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12989                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12990                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12991        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12992        msg.obj = params;
12993
12994        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12995                System.identityHashCode(msg.obj));
12996        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12997                System.identityHashCode(msg.obj));
12998
12999        mHandler.sendMessage(msg);
13000    }
13001
13002
13003    /**
13004     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13005     * it is acting on behalf on an enterprise or the user).
13006     *
13007     * Note that the ordering of the conditionals in this method is important. The checks we perform
13008     * are as follows, in this order:
13009     *
13010     * 1) If the install is being performed by a system app, we can trust the app to have set the
13011     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13012     *    what it is.
13013     * 2) If the install is being performed by a device or profile owner app, the install reason
13014     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13015     *    set the install reason correctly. If the app targets an older SDK version where install
13016     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13017     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13018     * 3) In all other cases, the install is being performed by a regular app that is neither part
13019     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13020     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13021     *    set to enterprise policy and if so, change it to unknown instead.
13022     */
13023    private int fixUpInstallReason(String installerPackageName, int installerUid,
13024            int installReason) {
13025        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13026                == PERMISSION_GRANTED) {
13027            // If the install is being performed by a system app, we trust that app to have set the
13028            // install reason correctly.
13029            return installReason;
13030        }
13031
13032        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13033            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13034        if (dpm != null) {
13035            ComponentName owner = null;
13036            try {
13037                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13038                if (owner == null) {
13039                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13040                }
13041            } catch (RemoteException e) {
13042            }
13043            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13044                // If the install is being performed by a device or profile owner, the install
13045                // reason should be enterprise policy.
13046                return PackageManager.INSTALL_REASON_POLICY;
13047            }
13048        }
13049
13050        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13051            // If the install is being performed by a regular app (i.e. neither system app nor
13052            // device or profile owner), we have no reason to believe that the app is acting on
13053            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13054            // change it to unknown instead.
13055            return PackageManager.INSTALL_REASON_UNKNOWN;
13056        }
13057
13058        // If the install is being performed by a regular app and the install reason was set to any
13059        // value but enterprise policy, leave the install reason unchanged.
13060        return installReason;
13061    }
13062
13063    void installStage(String packageName, File stagedDir, String stagedCid,
13064            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13065            String installerPackageName, int installerUid, UserHandle user,
13066            Certificate[][] certificates) {
13067        if (DEBUG_EPHEMERAL) {
13068            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13069                Slog.d(TAG, "Ephemeral install of " + packageName);
13070            }
13071        }
13072        final VerificationInfo verificationInfo = new VerificationInfo(
13073                sessionParams.originatingUri, sessionParams.referrerUri,
13074                sessionParams.originatingUid, installerUid);
13075
13076        final OriginInfo origin;
13077        if (stagedDir != null) {
13078            origin = OriginInfo.fromStagedFile(stagedDir);
13079        } else {
13080            origin = OriginInfo.fromStagedContainer(stagedCid);
13081        }
13082
13083        final Message msg = mHandler.obtainMessage(INIT_COPY);
13084        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13085                sessionParams.installReason);
13086        final InstallParams params = new InstallParams(origin, null, observer,
13087                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13088                verificationInfo, user, sessionParams.abiOverride,
13089                sessionParams.grantedRuntimePermissions, certificates, installReason);
13090        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13091        msg.obj = params;
13092
13093        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13094                System.identityHashCode(msg.obj));
13095        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13096                System.identityHashCode(msg.obj));
13097
13098        mHandler.sendMessage(msg);
13099    }
13100
13101    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13102            int userId) {
13103        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13104        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13105    }
13106
13107    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13108            int appId, int... userIds) {
13109        if (ArrayUtils.isEmpty(userIds)) {
13110            return;
13111        }
13112        Bundle extras = new Bundle(1);
13113        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13114        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13115
13116        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13117                packageName, extras, 0, null, null, userIds);
13118        if (isSystem) {
13119            mHandler.post(() -> {
13120                        for (int userId : userIds) {
13121                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13122                        }
13123                    }
13124            );
13125        }
13126    }
13127
13128    /**
13129     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13130     * automatically without needing an explicit launch.
13131     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13132     */
13133    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13134        // If user is not running, the app didn't miss any broadcast
13135        if (!mUserManagerInternal.isUserRunning(userId)) {
13136            return;
13137        }
13138        final IActivityManager am = ActivityManager.getService();
13139        try {
13140            // Deliver LOCKED_BOOT_COMPLETED first
13141            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13142                    .setPackage(packageName);
13143            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13144            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13145                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13146
13147            // Deliver BOOT_COMPLETED only if user is unlocked
13148            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13149                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13150                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13151                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13152            }
13153        } catch (RemoteException e) {
13154            throw e.rethrowFromSystemServer();
13155        }
13156    }
13157
13158    @Override
13159    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13160            int userId) {
13161        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13162        PackageSetting pkgSetting;
13163        final int uid = Binder.getCallingUid();
13164        enforceCrossUserPermission(uid, userId,
13165                true /* requireFullPermission */, true /* checkShell */,
13166                "setApplicationHiddenSetting for user " + userId);
13167
13168        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13169            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13170            return false;
13171        }
13172
13173        long callingId = Binder.clearCallingIdentity();
13174        try {
13175            boolean sendAdded = false;
13176            boolean sendRemoved = false;
13177            // writer
13178            synchronized (mPackages) {
13179                pkgSetting = mSettings.mPackages.get(packageName);
13180                if (pkgSetting == null) {
13181                    return false;
13182                }
13183                // Do not allow "android" is being disabled
13184                if ("android".equals(packageName)) {
13185                    Slog.w(TAG, "Cannot hide package: android");
13186                    return false;
13187                }
13188                // Cannot hide static shared libs as they are considered
13189                // a part of the using app (emulating static linking). Also
13190                // static libs are installed always on internal storage.
13191                PackageParser.Package pkg = mPackages.get(packageName);
13192                if (pkg != null && pkg.staticSharedLibName != null) {
13193                    Slog.w(TAG, "Cannot hide package: " + packageName
13194                            + " providing static shared library: "
13195                            + pkg.staticSharedLibName);
13196                    return false;
13197                }
13198                // Only allow protected packages to hide themselves.
13199                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13200                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13201                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13202                    return false;
13203                }
13204
13205                if (pkgSetting.getHidden(userId) != hidden) {
13206                    pkgSetting.setHidden(hidden, userId);
13207                    mSettings.writePackageRestrictionsLPr(userId);
13208                    if (hidden) {
13209                        sendRemoved = true;
13210                    } else {
13211                        sendAdded = true;
13212                    }
13213                }
13214            }
13215            if (sendAdded) {
13216                sendPackageAddedForUser(packageName, pkgSetting, userId);
13217                return true;
13218            }
13219            if (sendRemoved) {
13220                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13221                        "hiding pkg");
13222                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13223                return true;
13224            }
13225        } finally {
13226            Binder.restoreCallingIdentity(callingId);
13227        }
13228        return false;
13229    }
13230
13231    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13232            int userId) {
13233        final PackageRemovedInfo info = new PackageRemovedInfo();
13234        info.removedPackage = packageName;
13235        info.removedUsers = new int[] {userId};
13236        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13237        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13238    }
13239
13240    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13241        if (pkgList.length > 0) {
13242            Bundle extras = new Bundle(1);
13243            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13244
13245            sendPackageBroadcast(
13246                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13247                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13248                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13249                    new int[] {userId});
13250        }
13251    }
13252
13253    /**
13254     * Returns true if application is not found or there was an error. Otherwise it returns
13255     * the hidden state of the package for the given user.
13256     */
13257    @Override
13258    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13259        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13260        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13261                true /* requireFullPermission */, false /* checkShell */,
13262                "getApplicationHidden for user " + userId);
13263        PackageSetting pkgSetting;
13264        long callingId = Binder.clearCallingIdentity();
13265        try {
13266            // writer
13267            synchronized (mPackages) {
13268                pkgSetting = mSettings.mPackages.get(packageName);
13269                if (pkgSetting == null) {
13270                    return true;
13271                }
13272                return pkgSetting.getHidden(userId);
13273            }
13274        } finally {
13275            Binder.restoreCallingIdentity(callingId);
13276        }
13277    }
13278
13279    /**
13280     * @hide
13281     */
13282    @Override
13283    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13284            int installReason) {
13285        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13286                null);
13287        PackageSetting pkgSetting;
13288        final int uid = Binder.getCallingUid();
13289        enforceCrossUserPermission(uid, userId,
13290                true /* requireFullPermission */, true /* checkShell */,
13291                "installExistingPackage for user " + userId);
13292        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13293            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13294        }
13295
13296        long callingId = Binder.clearCallingIdentity();
13297        try {
13298            boolean installed = false;
13299            final boolean instantApp =
13300                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13301            final boolean fullApp =
13302                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13303
13304            // writer
13305            synchronized (mPackages) {
13306                pkgSetting = mSettings.mPackages.get(packageName);
13307                if (pkgSetting == null) {
13308                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13309                }
13310                if (!pkgSetting.getInstalled(userId)) {
13311                    pkgSetting.setInstalled(true, userId);
13312                    pkgSetting.setHidden(false, userId);
13313                    pkgSetting.setInstallReason(installReason, userId);
13314                    mSettings.writePackageRestrictionsLPr(userId);
13315                    mSettings.writeKernelMappingLPr(pkgSetting);
13316                    installed = true;
13317                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13318                    // upgrade app from instant to full; we don't allow app downgrade
13319                    installed = true;
13320                }
13321                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13322            }
13323
13324            if (installed) {
13325                if (pkgSetting.pkg != null) {
13326                    synchronized (mInstallLock) {
13327                        // We don't need to freeze for a brand new install
13328                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13329                    }
13330                }
13331                sendPackageAddedForUser(packageName, pkgSetting, userId);
13332                synchronized (mPackages) {
13333                    updateSequenceNumberLP(packageName, new int[]{ userId });
13334                }
13335            }
13336        } finally {
13337            Binder.restoreCallingIdentity(callingId);
13338        }
13339
13340        return PackageManager.INSTALL_SUCCEEDED;
13341    }
13342
13343    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13344            boolean instantApp, boolean fullApp) {
13345        // no state specified; do nothing
13346        if (!instantApp && !fullApp) {
13347            return;
13348        }
13349        if (userId != UserHandle.USER_ALL) {
13350            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13351                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13352            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13353                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13354            }
13355        } else {
13356            for (int currentUserId : sUserManager.getUserIds()) {
13357                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13358                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13359                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13360                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13361                }
13362            }
13363        }
13364    }
13365
13366    boolean isUserRestricted(int userId, String restrictionKey) {
13367        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13368        if (restrictions.getBoolean(restrictionKey, false)) {
13369            Log.w(TAG, "User is restricted: " + restrictionKey);
13370            return true;
13371        }
13372        return false;
13373    }
13374
13375    @Override
13376    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13377            int userId) {
13378        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13380                true /* requireFullPermission */, true /* checkShell */,
13381                "setPackagesSuspended for user " + userId);
13382
13383        if (ArrayUtils.isEmpty(packageNames)) {
13384            return packageNames;
13385        }
13386
13387        // List of package names for whom the suspended state has changed.
13388        List<String> changedPackages = new ArrayList<>(packageNames.length);
13389        // List of package names for whom the suspended state is not set as requested in this
13390        // method.
13391        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13392        long callingId = Binder.clearCallingIdentity();
13393        try {
13394            for (int i = 0; i < packageNames.length; i++) {
13395                String packageName = packageNames[i];
13396                boolean changed = false;
13397                final int appId;
13398                synchronized (mPackages) {
13399                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13400                    if (pkgSetting == null) {
13401                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13402                                + "\". Skipping suspending/un-suspending.");
13403                        unactionedPackages.add(packageName);
13404                        continue;
13405                    }
13406                    appId = pkgSetting.appId;
13407                    if (pkgSetting.getSuspended(userId) != suspended) {
13408                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13409                            unactionedPackages.add(packageName);
13410                            continue;
13411                        }
13412                        pkgSetting.setSuspended(suspended, userId);
13413                        mSettings.writePackageRestrictionsLPr(userId);
13414                        changed = true;
13415                        changedPackages.add(packageName);
13416                    }
13417                }
13418
13419                if (changed && suspended) {
13420                    killApplication(packageName, UserHandle.getUid(userId, appId),
13421                            "suspending package");
13422                }
13423            }
13424        } finally {
13425            Binder.restoreCallingIdentity(callingId);
13426        }
13427
13428        if (!changedPackages.isEmpty()) {
13429            sendPackagesSuspendedForUser(changedPackages.toArray(
13430                    new String[changedPackages.size()]), userId, suspended);
13431        }
13432
13433        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13434    }
13435
13436    @Override
13437    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13438        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13439                true /* requireFullPermission */, false /* checkShell */,
13440                "isPackageSuspendedForUser for user " + userId);
13441        synchronized (mPackages) {
13442            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13443            if (pkgSetting == null) {
13444                throw new IllegalArgumentException("Unknown target package: " + packageName);
13445            }
13446            return pkgSetting.getSuspended(userId);
13447        }
13448    }
13449
13450    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13451        if (isPackageDeviceAdmin(packageName, userId)) {
13452            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13453                    + "\": has an active device admin");
13454            return false;
13455        }
13456
13457        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13458        if (packageName.equals(activeLauncherPackageName)) {
13459            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13460                    + "\": contains the active launcher");
13461            return false;
13462        }
13463
13464        if (packageName.equals(mRequiredInstallerPackage)) {
13465            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13466                    + "\": required for package installation");
13467            return false;
13468        }
13469
13470        if (packageName.equals(mRequiredUninstallerPackage)) {
13471            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13472                    + "\": required for package uninstallation");
13473            return false;
13474        }
13475
13476        if (packageName.equals(mRequiredVerifierPackage)) {
13477            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13478                    + "\": required for package verification");
13479            return false;
13480        }
13481
13482        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13483            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13484                    + "\": is the default dialer");
13485            return false;
13486        }
13487
13488        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13489            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13490                    + "\": protected package");
13491            return false;
13492        }
13493
13494        // Cannot suspend static shared libs as they are considered
13495        // a part of the using app (emulating static linking). Also
13496        // static libs are installed always on internal storage.
13497        PackageParser.Package pkg = mPackages.get(packageName);
13498        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13499            Slog.w(TAG, "Cannot suspend package: " + packageName
13500                    + " providing static shared library: "
13501                    + pkg.staticSharedLibName);
13502            return false;
13503        }
13504
13505        return true;
13506    }
13507
13508    private String getActiveLauncherPackageName(int userId) {
13509        Intent intent = new Intent(Intent.ACTION_MAIN);
13510        intent.addCategory(Intent.CATEGORY_HOME);
13511        ResolveInfo resolveInfo = resolveIntent(
13512                intent,
13513                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13514                PackageManager.MATCH_DEFAULT_ONLY,
13515                userId);
13516
13517        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13518    }
13519
13520    private String getDefaultDialerPackageName(int userId) {
13521        synchronized (mPackages) {
13522            return mSettings.getDefaultDialerPackageNameLPw(userId);
13523        }
13524    }
13525
13526    @Override
13527    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13528        mContext.enforceCallingOrSelfPermission(
13529                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13530                "Only package verification agents can verify applications");
13531
13532        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13533        final PackageVerificationResponse response = new PackageVerificationResponse(
13534                verificationCode, Binder.getCallingUid());
13535        msg.arg1 = id;
13536        msg.obj = response;
13537        mHandler.sendMessage(msg);
13538    }
13539
13540    @Override
13541    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13542            long millisecondsToDelay) {
13543        mContext.enforceCallingOrSelfPermission(
13544                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13545                "Only package verification agents can extend verification timeouts");
13546
13547        final PackageVerificationState state = mPendingVerification.get(id);
13548        final PackageVerificationResponse response = new PackageVerificationResponse(
13549                verificationCodeAtTimeout, Binder.getCallingUid());
13550
13551        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13552            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13553        }
13554        if (millisecondsToDelay < 0) {
13555            millisecondsToDelay = 0;
13556        }
13557        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13558                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13559            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13560        }
13561
13562        if ((state != null) && !state.timeoutExtended()) {
13563            state.extendTimeout();
13564
13565            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13566            msg.arg1 = id;
13567            msg.obj = response;
13568            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13569        }
13570    }
13571
13572    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13573            int verificationCode, UserHandle user) {
13574        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13575        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13576        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13577        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13578        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13579
13580        mContext.sendBroadcastAsUser(intent, user,
13581                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13582    }
13583
13584    private ComponentName matchComponentForVerifier(String packageName,
13585            List<ResolveInfo> receivers) {
13586        ActivityInfo targetReceiver = null;
13587
13588        final int NR = receivers.size();
13589        for (int i = 0; i < NR; i++) {
13590            final ResolveInfo info = receivers.get(i);
13591            if (info.activityInfo == null) {
13592                continue;
13593            }
13594
13595            if (packageName.equals(info.activityInfo.packageName)) {
13596                targetReceiver = info.activityInfo;
13597                break;
13598            }
13599        }
13600
13601        if (targetReceiver == null) {
13602            return null;
13603        }
13604
13605        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13606    }
13607
13608    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13609            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13610        if (pkgInfo.verifiers.length == 0) {
13611            return null;
13612        }
13613
13614        final int N = pkgInfo.verifiers.length;
13615        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13616        for (int i = 0; i < N; i++) {
13617            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13618
13619            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13620                    receivers);
13621            if (comp == null) {
13622                continue;
13623            }
13624
13625            final int verifierUid = getUidForVerifier(verifierInfo);
13626            if (verifierUid == -1) {
13627                continue;
13628            }
13629
13630            if (DEBUG_VERIFY) {
13631                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13632                        + " with the correct signature");
13633            }
13634            sufficientVerifiers.add(comp);
13635            verificationState.addSufficientVerifier(verifierUid);
13636        }
13637
13638        return sufficientVerifiers;
13639    }
13640
13641    private int getUidForVerifier(VerifierInfo verifierInfo) {
13642        synchronized (mPackages) {
13643            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13644            if (pkg == null) {
13645                return -1;
13646            } else if (pkg.mSignatures.length != 1) {
13647                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13648                        + " has more than one signature; ignoring");
13649                return -1;
13650            }
13651
13652            /*
13653             * If the public key of the package's signature does not match
13654             * our expected public key, then this is a different package and
13655             * we should skip.
13656             */
13657
13658            final byte[] expectedPublicKey;
13659            try {
13660                final Signature verifierSig = pkg.mSignatures[0];
13661                final PublicKey publicKey = verifierSig.getPublicKey();
13662                expectedPublicKey = publicKey.getEncoded();
13663            } catch (CertificateException e) {
13664                return -1;
13665            }
13666
13667            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13668
13669            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13670                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13671                        + " does not have the expected public key; ignoring");
13672                return -1;
13673            }
13674
13675            return pkg.applicationInfo.uid;
13676        }
13677    }
13678
13679    @Override
13680    public void finishPackageInstall(int token, boolean didLaunch) {
13681        enforceSystemOrRoot("Only the system is allowed to finish installs");
13682
13683        if (DEBUG_INSTALL) {
13684            Slog.v(TAG, "BM finishing package install for " + token);
13685        }
13686        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13687
13688        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13689        mHandler.sendMessage(msg);
13690    }
13691
13692    /**
13693     * Get the verification agent timeout.
13694     *
13695     * @return verification timeout in milliseconds
13696     */
13697    private long getVerificationTimeout() {
13698        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13699                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13700                DEFAULT_VERIFICATION_TIMEOUT);
13701    }
13702
13703    /**
13704     * Get the default verification agent response code.
13705     *
13706     * @return default verification response code
13707     */
13708    private int getDefaultVerificationResponse() {
13709        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13710                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13711                DEFAULT_VERIFICATION_RESPONSE);
13712    }
13713
13714    /**
13715     * Check whether or not package verification has been enabled.
13716     *
13717     * @return true if verification should be performed
13718     */
13719    private boolean isVerificationEnabled(int userId, int installFlags) {
13720        if (!DEFAULT_VERIFY_ENABLE) {
13721            return false;
13722        }
13723
13724        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13725
13726        // Check if installing from ADB
13727        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13728            // Do not run verification in a test harness environment
13729            if (ActivityManager.isRunningInTestHarness()) {
13730                return false;
13731            }
13732            if (ensureVerifyAppsEnabled) {
13733                return true;
13734            }
13735            // Check if the developer does not want package verification for ADB installs
13736            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13737                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13738                return false;
13739            }
13740        }
13741
13742        if (ensureVerifyAppsEnabled) {
13743            return true;
13744        }
13745
13746        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13747                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13748    }
13749
13750    @Override
13751    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13752            throws RemoteException {
13753        mContext.enforceCallingOrSelfPermission(
13754                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13755                "Only intentfilter verification agents can verify applications");
13756
13757        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13758        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13759                Binder.getCallingUid(), verificationCode, failedDomains);
13760        msg.arg1 = id;
13761        msg.obj = response;
13762        mHandler.sendMessage(msg);
13763    }
13764
13765    @Override
13766    public int getIntentVerificationStatus(String packageName, int userId) {
13767        synchronized (mPackages) {
13768            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13769        }
13770    }
13771
13772    @Override
13773    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13774        mContext.enforceCallingOrSelfPermission(
13775                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13776
13777        boolean result = false;
13778        synchronized (mPackages) {
13779            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13780        }
13781        if (result) {
13782            scheduleWritePackageRestrictionsLocked(userId);
13783        }
13784        return result;
13785    }
13786
13787    @Override
13788    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13789            String packageName) {
13790        synchronized (mPackages) {
13791            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13792        }
13793    }
13794
13795    @Override
13796    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13797        if (TextUtils.isEmpty(packageName)) {
13798            return ParceledListSlice.emptyList();
13799        }
13800        synchronized (mPackages) {
13801            PackageParser.Package pkg = mPackages.get(packageName);
13802            if (pkg == null || pkg.activities == null) {
13803                return ParceledListSlice.emptyList();
13804            }
13805            final int count = pkg.activities.size();
13806            ArrayList<IntentFilter> result = new ArrayList<>();
13807            for (int n=0; n<count; n++) {
13808                PackageParser.Activity activity = pkg.activities.get(n);
13809                if (activity.intents != null && activity.intents.size() > 0) {
13810                    result.addAll(activity.intents);
13811                }
13812            }
13813            return new ParceledListSlice<>(result);
13814        }
13815    }
13816
13817    @Override
13818    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13819        mContext.enforceCallingOrSelfPermission(
13820                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13821
13822        synchronized (mPackages) {
13823            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13824            if (packageName != null) {
13825                result |= updateIntentVerificationStatus(packageName,
13826                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13827                        userId);
13828                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13829                        packageName, userId);
13830            }
13831            return result;
13832        }
13833    }
13834
13835    @Override
13836    public String getDefaultBrowserPackageName(int userId) {
13837        synchronized (mPackages) {
13838            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13839        }
13840    }
13841
13842    /**
13843     * Get the "allow unknown sources" setting.
13844     *
13845     * @return the current "allow unknown sources" setting
13846     */
13847    private int getUnknownSourcesSettings() {
13848        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13849                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13850                -1);
13851    }
13852
13853    @Override
13854    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13855        final int uid = Binder.getCallingUid();
13856        // writer
13857        synchronized (mPackages) {
13858            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13859            if (targetPackageSetting == null) {
13860                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13861            }
13862
13863            PackageSetting installerPackageSetting;
13864            if (installerPackageName != null) {
13865                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13866                if (installerPackageSetting == null) {
13867                    throw new IllegalArgumentException("Unknown installer package: "
13868                            + installerPackageName);
13869                }
13870            } else {
13871                installerPackageSetting = null;
13872            }
13873
13874            Signature[] callerSignature;
13875            Object obj = mSettings.getUserIdLPr(uid);
13876            if (obj != null) {
13877                if (obj instanceof SharedUserSetting) {
13878                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13879                } else if (obj instanceof PackageSetting) {
13880                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13881                } else {
13882                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13883                }
13884            } else {
13885                throw new SecurityException("Unknown calling UID: " + uid);
13886            }
13887
13888            // Verify: can't set installerPackageName to a package that is
13889            // not signed with the same cert as the caller.
13890            if (installerPackageSetting != null) {
13891                if (compareSignatures(callerSignature,
13892                        installerPackageSetting.signatures.mSignatures)
13893                        != PackageManager.SIGNATURE_MATCH) {
13894                    throw new SecurityException(
13895                            "Caller does not have same cert as new installer package "
13896                            + installerPackageName);
13897                }
13898            }
13899
13900            // Verify: if target already has an installer package, it must
13901            // be signed with the same cert as the caller.
13902            if (targetPackageSetting.installerPackageName != null) {
13903                PackageSetting setting = mSettings.mPackages.get(
13904                        targetPackageSetting.installerPackageName);
13905                // If the currently set package isn't valid, then it's always
13906                // okay to change it.
13907                if (setting != null) {
13908                    if (compareSignatures(callerSignature,
13909                            setting.signatures.mSignatures)
13910                            != PackageManager.SIGNATURE_MATCH) {
13911                        throw new SecurityException(
13912                                "Caller does not have same cert as old installer package "
13913                                + targetPackageSetting.installerPackageName);
13914                    }
13915                }
13916            }
13917
13918            // Okay!
13919            targetPackageSetting.installerPackageName = installerPackageName;
13920            if (installerPackageName != null) {
13921                mSettings.mInstallerPackages.add(installerPackageName);
13922            }
13923            scheduleWriteSettingsLocked();
13924        }
13925    }
13926
13927    @Override
13928    public void setApplicationCategoryHint(String packageName, int categoryHint,
13929            String callerPackageName) {
13930        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13931                callerPackageName);
13932        synchronized (mPackages) {
13933            PackageSetting ps = mSettings.mPackages.get(packageName);
13934            if (ps == null) {
13935                throw new IllegalArgumentException("Unknown target package " + packageName);
13936            }
13937
13938            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13939                throw new IllegalArgumentException("Calling package " + callerPackageName
13940                        + " is not installer for " + packageName);
13941            }
13942
13943            if (ps.categoryHint != categoryHint) {
13944                ps.categoryHint = categoryHint;
13945                scheduleWriteSettingsLocked();
13946            }
13947        }
13948    }
13949
13950    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13951        // Queue up an async operation since the package installation may take a little while.
13952        mHandler.post(new Runnable() {
13953            public void run() {
13954                mHandler.removeCallbacks(this);
13955                 // Result object to be returned
13956                PackageInstalledInfo res = new PackageInstalledInfo();
13957                res.setReturnCode(currentStatus);
13958                res.uid = -1;
13959                res.pkg = null;
13960                res.removedInfo = null;
13961                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13962                    args.doPreInstall(res.returnCode);
13963                    synchronized (mInstallLock) {
13964                        installPackageTracedLI(args, res);
13965                    }
13966                    args.doPostInstall(res.returnCode, res.uid);
13967                }
13968
13969                // A restore should be performed at this point if (a) the install
13970                // succeeded, (b) the operation is not an update, and (c) the new
13971                // package has not opted out of backup participation.
13972                final boolean update = res.removedInfo != null
13973                        && res.removedInfo.removedPackage != null;
13974                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13975                boolean doRestore = !update
13976                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13977
13978                // Set up the post-install work request bookkeeping.  This will be used
13979                // and cleaned up by the post-install event handling regardless of whether
13980                // there's a restore pass performed.  Token values are >= 1.
13981                int token;
13982                if (mNextInstallToken < 0) mNextInstallToken = 1;
13983                token = mNextInstallToken++;
13984
13985                PostInstallData data = new PostInstallData(args, res);
13986                mRunningInstalls.put(token, data);
13987                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13988
13989                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13990                    // Pass responsibility to the Backup Manager.  It will perform a
13991                    // restore if appropriate, then pass responsibility back to the
13992                    // Package Manager to run the post-install observer callbacks
13993                    // and broadcasts.
13994                    IBackupManager bm = IBackupManager.Stub.asInterface(
13995                            ServiceManager.getService(Context.BACKUP_SERVICE));
13996                    if (bm != null) {
13997                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13998                                + " to BM for possible restore");
13999                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14000                        try {
14001                            // TODO: http://b/22388012
14002                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14003                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14004                            } else {
14005                                doRestore = false;
14006                            }
14007                        } catch (RemoteException e) {
14008                            // can't happen; the backup manager is local
14009                        } catch (Exception e) {
14010                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14011                            doRestore = false;
14012                        }
14013                    } else {
14014                        Slog.e(TAG, "Backup Manager not found!");
14015                        doRestore = false;
14016                    }
14017                }
14018
14019                if (!doRestore) {
14020                    // No restore possible, or the Backup Manager was mysteriously not
14021                    // available -- just fire the post-install work request directly.
14022                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14023
14024                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14025
14026                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14027                    mHandler.sendMessage(msg);
14028                }
14029            }
14030        });
14031    }
14032
14033    /**
14034     * Callback from PackageSettings whenever an app is first transitioned out of the
14035     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14036     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14037     * here whether the app is the target of an ongoing install, and only send the
14038     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14039     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14040     * handling.
14041     */
14042    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14043        // Serialize this with the rest of the install-process message chain.  In the
14044        // restore-at-install case, this Runnable will necessarily run before the
14045        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14046        // are coherent.  In the non-restore case, the app has already completed install
14047        // and been launched through some other means, so it is not in a problematic
14048        // state for observers to see the FIRST_LAUNCH signal.
14049        mHandler.post(new Runnable() {
14050            @Override
14051            public void run() {
14052                for (int i = 0; i < mRunningInstalls.size(); i++) {
14053                    final PostInstallData data = mRunningInstalls.valueAt(i);
14054                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14055                        continue;
14056                    }
14057                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14058                        // right package; but is it for the right user?
14059                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14060                            if (userId == data.res.newUsers[uIndex]) {
14061                                if (DEBUG_BACKUP) {
14062                                    Slog.i(TAG, "Package " + pkgName
14063                                            + " being restored so deferring FIRST_LAUNCH");
14064                                }
14065                                return;
14066                            }
14067                        }
14068                    }
14069                }
14070                // didn't find it, so not being restored
14071                if (DEBUG_BACKUP) {
14072                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14073                }
14074                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14075            }
14076        });
14077    }
14078
14079    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14080        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14081                installerPkg, null, userIds);
14082    }
14083
14084    private abstract class HandlerParams {
14085        private static final int MAX_RETRIES = 4;
14086
14087        /**
14088         * Number of times startCopy() has been attempted and had a non-fatal
14089         * error.
14090         */
14091        private int mRetries = 0;
14092
14093        /** User handle for the user requesting the information or installation. */
14094        private final UserHandle mUser;
14095        String traceMethod;
14096        int traceCookie;
14097
14098        HandlerParams(UserHandle user) {
14099            mUser = user;
14100        }
14101
14102        UserHandle getUser() {
14103            return mUser;
14104        }
14105
14106        HandlerParams setTraceMethod(String traceMethod) {
14107            this.traceMethod = traceMethod;
14108            return this;
14109        }
14110
14111        HandlerParams setTraceCookie(int traceCookie) {
14112            this.traceCookie = traceCookie;
14113            return this;
14114        }
14115
14116        final boolean startCopy() {
14117            boolean res;
14118            try {
14119                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14120
14121                if (++mRetries > MAX_RETRIES) {
14122                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14123                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14124                    handleServiceError();
14125                    return false;
14126                } else {
14127                    handleStartCopy();
14128                    res = true;
14129                }
14130            } catch (RemoteException e) {
14131                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14132                mHandler.sendEmptyMessage(MCS_RECONNECT);
14133                res = false;
14134            }
14135            handleReturnCode();
14136            return res;
14137        }
14138
14139        final void serviceError() {
14140            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14141            handleServiceError();
14142            handleReturnCode();
14143        }
14144
14145        abstract void handleStartCopy() throws RemoteException;
14146        abstract void handleServiceError();
14147        abstract void handleReturnCode();
14148    }
14149
14150    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14151        for (File path : paths) {
14152            try {
14153                mcs.clearDirectory(path.getAbsolutePath());
14154            } catch (RemoteException e) {
14155            }
14156        }
14157    }
14158
14159    static class OriginInfo {
14160        /**
14161         * Location where install is coming from, before it has been
14162         * copied/renamed into place. This could be a single monolithic APK
14163         * file, or a cluster directory. This location may be untrusted.
14164         */
14165        final File file;
14166        final String cid;
14167
14168        /**
14169         * Flag indicating that {@link #file} or {@link #cid} has already been
14170         * staged, meaning downstream users don't need to defensively copy the
14171         * contents.
14172         */
14173        final boolean staged;
14174
14175        /**
14176         * Flag indicating that {@link #file} or {@link #cid} is an already
14177         * installed app that is being moved.
14178         */
14179        final boolean existing;
14180
14181        final String resolvedPath;
14182        final File resolvedFile;
14183
14184        static OriginInfo fromNothing() {
14185            return new OriginInfo(null, null, false, false);
14186        }
14187
14188        static OriginInfo fromUntrustedFile(File file) {
14189            return new OriginInfo(file, null, false, false);
14190        }
14191
14192        static OriginInfo fromExistingFile(File file) {
14193            return new OriginInfo(file, null, false, true);
14194        }
14195
14196        static OriginInfo fromStagedFile(File file) {
14197            return new OriginInfo(file, null, true, false);
14198        }
14199
14200        static OriginInfo fromStagedContainer(String cid) {
14201            return new OriginInfo(null, cid, true, false);
14202        }
14203
14204        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14205            this.file = file;
14206            this.cid = cid;
14207            this.staged = staged;
14208            this.existing = existing;
14209
14210            if (cid != null) {
14211                resolvedPath = PackageHelper.getSdDir(cid);
14212                resolvedFile = new File(resolvedPath);
14213            } else if (file != null) {
14214                resolvedPath = file.getAbsolutePath();
14215                resolvedFile = file;
14216            } else {
14217                resolvedPath = null;
14218                resolvedFile = null;
14219            }
14220        }
14221    }
14222
14223    static class MoveInfo {
14224        final int moveId;
14225        final String fromUuid;
14226        final String toUuid;
14227        final String packageName;
14228        final String dataAppName;
14229        final int appId;
14230        final String seinfo;
14231        final int targetSdkVersion;
14232
14233        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14234                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14235            this.moveId = moveId;
14236            this.fromUuid = fromUuid;
14237            this.toUuid = toUuid;
14238            this.packageName = packageName;
14239            this.dataAppName = dataAppName;
14240            this.appId = appId;
14241            this.seinfo = seinfo;
14242            this.targetSdkVersion = targetSdkVersion;
14243        }
14244    }
14245
14246    static class VerificationInfo {
14247        /** A constant used to indicate that a uid value is not present. */
14248        public static final int NO_UID = -1;
14249
14250        /** URI referencing where the package was downloaded from. */
14251        final Uri originatingUri;
14252
14253        /** HTTP referrer URI associated with the originatingURI. */
14254        final Uri referrer;
14255
14256        /** UID of the application that the install request originated from. */
14257        final int originatingUid;
14258
14259        /** UID of application requesting the install */
14260        final int installerUid;
14261
14262        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14263            this.originatingUri = originatingUri;
14264            this.referrer = referrer;
14265            this.originatingUid = originatingUid;
14266            this.installerUid = installerUid;
14267        }
14268    }
14269
14270    class InstallParams extends HandlerParams {
14271        final OriginInfo origin;
14272        final MoveInfo move;
14273        final IPackageInstallObserver2 observer;
14274        int installFlags;
14275        final String installerPackageName;
14276        final String volumeUuid;
14277        private InstallArgs mArgs;
14278        private int mRet;
14279        final String packageAbiOverride;
14280        final String[] grantedRuntimePermissions;
14281        final VerificationInfo verificationInfo;
14282        final Certificate[][] certificates;
14283        final int installReason;
14284
14285        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14286                int installFlags, String installerPackageName, String volumeUuid,
14287                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14288                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14289            super(user);
14290            this.origin = origin;
14291            this.move = move;
14292            this.observer = observer;
14293            this.installFlags = installFlags;
14294            this.installerPackageName = installerPackageName;
14295            this.volumeUuid = volumeUuid;
14296            this.verificationInfo = verificationInfo;
14297            this.packageAbiOverride = packageAbiOverride;
14298            this.grantedRuntimePermissions = grantedPermissions;
14299            this.certificates = certificates;
14300            this.installReason = installReason;
14301        }
14302
14303        @Override
14304        public String toString() {
14305            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14306                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14307        }
14308
14309        private int installLocationPolicy(PackageInfoLite pkgLite) {
14310            String packageName = pkgLite.packageName;
14311            int installLocation = pkgLite.installLocation;
14312            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14313            // reader
14314            synchronized (mPackages) {
14315                // Currently installed package which the new package is attempting to replace or
14316                // null if no such package is installed.
14317                PackageParser.Package installedPkg = mPackages.get(packageName);
14318                // Package which currently owns the data which the new package will own if installed.
14319                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14320                // will be null whereas dataOwnerPkg will contain information about the package
14321                // which was uninstalled while keeping its data.
14322                PackageParser.Package dataOwnerPkg = installedPkg;
14323                if (dataOwnerPkg  == null) {
14324                    PackageSetting ps = mSettings.mPackages.get(packageName);
14325                    if (ps != null) {
14326                        dataOwnerPkg = ps.pkg;
14327                    }
14328                }
14329
14330                if (dataOwnerPkg != null) {
14331                    // If installed, the package will get access to data left on the device by its
14332                    // predecessor. As a security measure, this is permited only if this is not a
14333                    // version downgrade or if the predecessor package is marked as debuggable and
14334                    // a downgrade is explicitly requested.
14335                    //
14336                    // On debuggable platform builds, downgrades are permitted even for
14337                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14338                    // not offer security guarantees and thus it's OK to disable some security
14339                    // mechanisms to make debugging/testing easier on those builds. However, even on
14340                    // debuggable builds downgrades of packages are permitted only if requested via
14341                    // installFlags. This is because we aim to keep the behavior of debuggable
14342                    // platform builds as close as possible to the behavior of non-debuggable
14343                    // platform builds.
14344                    final boolean downgradeRequested =
14345                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14346                    final boolean packageDebuggable =
14347                                (dataOwnerPkg.applicationInfo.flags
14348                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14349                    final boolean downgradePermitted =
14350                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14351                    if (!downgradePermitted) {
14352                        try {
14353                            checkDowngrade(dataOwnerPkg, pkgLite);
14354                        } catch (PackageManagerException e) {
14355                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14356                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14357                        }
14358                    }
14359                }
14360
14361                if (installedPkg != null) {
14362                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14363                        // Check for updated system application.
14364                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14365                            if (onSd) {
14366                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14367                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14368                            }
14369                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14370                        } else {
14371                            if (onSd) {
14372                                // Install flag overrides everything.
14373                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14374                            }
14375                            // If current upgrade specifies particular preference
14376                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14377                                // Application explicitly specified internal.
14378                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14379                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14380                                // App explictly prefers external. Let policy decide
14381                            } else {
14382                                // Prefer previous location
14383                                if (isExternal(installedPkg)) {
14384                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14385                                }
14386                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14387                            }
14388                        }
14389                    } else {
14390                        // Invalid install. Return error code
14391                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14392                    }
14393                }
14394            }
14395            // All the special cases have been taken care of.
14396            // Return result based on recommended install location.
14397            if (onSd) {
14398                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14399            }
14400            return pkgLite.recommendedInstallLocation;
14401        }
14402
14403        /*
14404         * Invoke remote method to get package information and install
14405         * location values. Override install location based on default
14406         * policy if needed and then create install arguments based
14407         * on the install location.
14408         */
14409        public void handleStartCopy() throws RemoteException {
14410            int ret = PackageManager.INSTALL_SUCCEEDED;
14411
14412            // If we're already staged, we've firmly committed to an install location
14413            if (origin.staged) {
14414                if (origin.file != null) {
14415                    installFlags |= PackageManager.INSTALL_INTERNAL;
14416                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14417                } else if (origin.cid != null) {
14418                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14419                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14420                } else {
14421                    throw new IllegalStateException("Invalid stage location");
14422                }
14423            }
14424
14425            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14426            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14427            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14428            PackageInfoLite pkgLite = null;
14429
14430            if (onInt && onSd) {
14431                // Check if both bits are set.
14432                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14433                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14434            } else if (onSd && ephemeral) {
14435                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14436                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14437            } else {
14438                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14439                        packageAbiOverride);
14440
14441                if (DEBUG_EPHEMERAL && ephemeral) {
14442                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14443                }
14444
14445                /*
14446                 * If we have too little free space, try to free cache
14447                 * before giving up.
14448                 */
14449                if (!origin.staged && pkgLite.recommendedInstallLocation
14450                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14451                    // TODO: focus freeing disk space on the target device
14452                    final StorageManager storage = StorageManager.from(mContext);
14453                    final long lowThreshold = storage.getStorageLowBytes(
14454                            Environment.getDataDirectory());
14455
14456                    final long sizeBytes = mContainerService.calculateInstalledSize(
14457                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14458
14459                    try {
14460                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14461                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14462                                installFlags, packageAbiOverride);
14463                    } catch (InstallerException e) {
14464                        Slog.w(TAG, "Failed to free cache", e);
14465                    }
14466
14467                    /*
14468                     * The cache free must have deleted the file we
14469                     * downloaded to install.
14470                     *
14471                     * TODO: fix the "freeCache" call to not delete
14472                     *       the file we care about.
14473                     */
14474                    if (pkgLite.recommendedInstallLocation
14475                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14476                        pkgLite.recommendedInstallLocation
14477                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14478                    }
14479                }
14480            }
14481
14482            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14483                int loc = pkgLite.recommendedInstallLocation;
14484                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14485                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14486                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14487                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14488                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14489                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14490                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14491                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14492                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14493                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14494                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14495                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14496                } else {
14497                    // Override with defaults if needed.
14498                    loc = installLocationPolicy(pkgLite);
14499                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14500                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14501                    } else if (!onSd && !onInt) {
14502                        // Override install location with flags
14503                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14504                            // Set the flag to install on external media.
14505                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14506                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14507                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14508                            if (DEBUG_EPHEMERAL) {
14509                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14510                            }
14511                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14512                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14513                                    |PackageManager.INSTALL_INTERNAL);
14514                        } else {
14515                            // Make sure the flag for installing on external
14516                            // media is unset
14517                            installFlags |= PackageManager.INSTALL_INTERNAL;
14518                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14519                        }
14520                    }
14521                }
14522            }
14523
14524            final InstallArgs args = createInstallArgs(this);
14525            mArgs = args;
14526
14527            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14528                // TODO: http://b/22976637
14529                // Apps installed for "all" users use the device owner to verify the app
14530                UserHandle verifierUser = getUser();
14531                if (verifierUser == UserHandle.ALL) {
14532                    verifierUser = UserHandle.SYSTEM;
14533                }
14534
14535                /*
14536                 * Determine if we have any installed package verifiers. If we
14537                 * do, then we'll defer to them to verify the packages.
14538                 */
14539                final int requiredUid = mRequiredVerifierPackage == null ? -1
14540                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14541                                verifierUser.getIdentifier());
14542                if (!origin.existing && requiredUid != -1
14543                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14544                    final Intent verification = new Intent(
14545                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14546                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14547                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14548                            PACKAGE_MIME_TYPE);
14549                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14550
14551                    // Query all live verifiers based on current user state
14552                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14553                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14554
14555                    if (DEBUG_VERIFY) {
14556                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14557                                + verification.toString() + " with " + pkgLite.verifiers.length
14558                                + " optional verifiers");
14559                    }
14560
14561                    final int verificationId = mPendingVerificationToken++;
14562
14563                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14564
14565                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14566                            installerPackageName);
14567
14568                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14569                            installFlags);
14570
14571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14572                            pkgLite.packageName);
14573
14574                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14575                            pkgLite.versionCode);
14576
14577                    if (verificationInfo != null) {
14578                        if (verificationInfo.originatingUri != null) {
14579                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14580                                    verificationInfo.originatingUri);
14581                        }
14582                        if (verificationInfo.referrer != null) {
14583                            verification.putExtra(Intent.EXTRA_REFERRER,
14584                                    verificationInfo.referrer);
14585                        }
14586                        if (verificationInfo.originatingUid >= 0) {
14587                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14588                                    verificationInfo.originatingUid);
14589                        }
14590                        if (verificationInfo.installerUid >= 0) {
14591                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14592                                    verificationInfo.installerUid);
14593                        }
14594                    }
14595
14596                    final PackageVerificationState verificationState = new PackageVerificationState(
14597                            requiredUid, args);
14598
14599                    mPendingVerification.append(verificationId, verificationState);
14600
14601                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14602                            receivers, verificationState);
14603
14604                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14605                    final long idleDuration = getVerificationTimeout();
14606
14607                    /*
14608                     * If any sufficient verifiers were listed in the package
14609                     * manifest, attempt to ask them.
14610                     */
14611                    if (sufficientVerifiers != null) {
14612                        final int N = sufficientVerifiers.size();
14613                        if (N == 0) {
14614                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14615                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14616                        } else {
14617                            for (int i = 0; i < N; i++) {
14618                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14619                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14620                                        verifierComponent.getPackageName(), idleDuration,
14621                                        verifierUser.getIdentifier(), false, "package verifier");
14622
14623                                final Intent sufficientIntent = new Intent(verification);
14624                                sufficientIntent.setComponent(verifierComponent);
14625                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14626                            }
14627                        }
14628                    }
14629
14630                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14631                            mRequiredVerifierPackage, receivers);
14632                    if (ret == PackageManager.INSTALL_SUCCEEDED
14633                            && mRequiredVerifierPackage != null) {
14634                        Trace.asyncTraceBegin(
14635                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14636                        /*
14637                         * Send the intent to the required verification agent,
14638                         * but only start the verification timeout after the
14639                         * target BroadcastReceivers have run.
14640                         */
14641                        verification.setComponent(requiredVerifierComponent);
14642                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14643                                mRequiredVerifierPackage, idleDuration,
14644                                verifierUser.getIdentifier(), false, "package verifier");
14645                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14646                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14647                                new BroadcastReceiver() {
14648                                    @Override
14649                                    public void onReceive(Context context, Intent intent) {
14650                                        final Message msg = mHandler
14651                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14652                                        msg.arg1 = verificationId;
14653                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14654                                    }
14655                                }, null, 0, null, null);
14656
14657                        /*
14658                         * We don't want the copy to proceed until verification
14659                         * succeeds, so null out this field.
14660                         */
14661                        mArgs = null;
14662                    }
14663                } else {
14664                    /*
14665                     * No package verification is enabled, so immediately start
14666                     * the remote call to initiate copy using temporary file.
14667                     */
14668                    ret = args.copyApk(mContainerService, true);
14669                }
14670            }
14671
14672            mRet = ret;
14673        }
14674
14675        @Override
14676        void handleReturnCode() {
14677            // If mArgs is null, then MCS couldn't be reached. When it
14678            // reconnects, it will try again to install. At that point, this
14679            // will succeed.
14680            if (mArgs != null) {
14681                processPendingInstall(mArgs, mRet);
14682            }
14683        }
14684
14685        @Override
14686        void handleServiceError() {
14687            mArgs = createInstallArgs(this);
14688            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14689        }
14690
14691        public boolean isForwardLocked() {
14692            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14693        }
14694    }
14695
14696    /**
14697     * Used during creation of InstallArgs
14698     *
14699     * @param installFlags package installation flags
14700     * @return true if should be installed on external storage
14701     */
14702    private static boolean installOnExternalAsec(int installFlags) {
14703        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14704            return false;
14705        }
14706        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14707            return true;
14708        }
14709        return false;
14710    }
14711
14712    /**
14713     * Used during creation of InstallArgs
14714     *
14715     * @param installFlags package installation flags
14716     * @return true if should be installed as forward locked
14717     */
14718    private static boolean installForwardLocked(int installFlags) {
14719        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14720    }
14721
14722    private InstallArgs createInstallArgs(InstallParams params) {
14723        if (params.move != null) {
14724            return new MoveInstallArgs(params);
14725        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14726            return new AsecInstallArgs(params);
14727        } else {
14728            return new FileInstallArgs(params);
14729        }
14730    }
14731
14732    /**
14733     * Create args that describe an existing installed package. Typically used
14734     * when cleaning up old installs, or used as a move source.
14735     */
14736    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14737            String resourcePath, String[] instructionSets) {
14738        final boolean isInAsec;
14739        if (installOnExternalAsec(installFlags)) {
14740            /* Apps on SD card are always in ASEC containers. */
14741            isInAsec = true;
14742        } else if (installForwardLocked(installFlags)
14743                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14744            /*
14745             * Forward-locked apps are only in ASEC containers if they're the
14746             * new style
14747             */
14748            isInAsec = true;
14749        } else {
14750            isInAsec = false;
14751        }
14752
14753        if (isInAsec) {
14754            return new AsecInstallArgs(codePath, instructionSets,
14755                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14756        } else {
14757            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14758        }
14759    }
14760
14761    static abstract class InstallArgs {
14762        /** @see InstallParams#origin */
14763        final OriginInfo origin;
14764        /** @see InstallParams#move */
14765        final MoveInfo move;
14766
14767        final IPackageInstallObserver2 observer;
14768        // Always refers to PackageManager flags only
14769        final int installFlags;
14770        final String installerPackageName;
14771        final String volumeUuid;
14772        final UserHandle user;
14773        final String abiOverride;
14774        final String[] installGrantPermissions;
14775        /** If non-null, drop an async trace when the install completes */
14776        final String traceMethod;
14777        final int traceCookie;
14778        final Certificate[][] certificates;
14779        final int installReason;
14780
14781        // The list of instruction sets supported by this app. This is currently
14782        // only used during the rmdex() phase to clean up resources. We can get rid of this
14783        // if we move dex files under the common app path.
14784        /* nullable */ String[] instructionSets;
14785
14786        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14787                int installFlags, String installerPackageName, String volumeUuid,
14788                UserHandle user, String[] instructionSets,
14789                String abiOverride, String[] installGrantPermissions,
14790                String traceMethod, int traceCookie, Certificate[][] certificates,
14791                int installReason) {
14792            this.origin = origin;
14793            this.move = move;
14794            this.installFlags = installFlags;
14795            this.observer = observer;
14796            this.installerPackageName = installerPackageName;
14797            this.volumeUuid = volumeUuid;
14798            this.user = user;
14799            this.instructionSets = instructionSets;
14800            this.abiOverride = abiOverride;
14801            this.installGrantPermissions = installGrantPermissions;
14802            this.traceMethod = traceMethod;
14803            this.traceCookie = traceCookie;
14804            this.certificates = certificates;
14805            this.installReason = installReason;
14806        }
14807
14808        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14809        abstract int doPreInstall(int status);
14810
14811        /**
14812         * Rename package into final resting place. All paths on the given
14813         * scanned package should be updated to reflect the rename.
14814         */
14815        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14816        abstract int doPostInstall(int status, int uid);
14817
14818        /** @see PackageSettingBase#codePathString */
14819        abstract String getCodePath();
14820        /** @see PackageSettingBase#resourcePathString */
14821        abstract String getResourcePath();
14822
14823        // Need installer lock especially for dex file removal.
14824        abstract void cleanUpResourcesLI();
14825        abstract boolean doPostDeleteLI(boolean delete);
14826
14827        /**
14828         * Called before the source arguments are copied. This is used mostly
14829         * for MoveParams when it needs to read the source file to put it in the
14830         * destination.
14831         */
14832        int doPreCopy() {
14833            return PackageManager.INSTALL_SUCCEEDED;
14834        }
14835
14836        /**
14837         * Called after the source arguments are copied. This is used mostly for
14838         * MoveParams when it needs to read the source file to put it in the
14839         * destination.
14840         */
14841        int doPostCopy(int uid) {
14842            return PackageManager.INSTALL_SUCCEEDED;
14843        }
14844
14845        protected boolean isFwdLocked() {
14846            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14847        }
14848
14849        protected boolean isExternalAsec() {
14850            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14851        }
14852
14853        protected boolean isEphemeral() {
14854            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14855        }
14856
14857        UserHandle getUser() {
14858            return user;
14859        }
14860    }
14861
14862    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14863        if (!allCodePaths.isEmpty()) {
14864            if (instructionSets == null) {
14865                throw new IllegalStateException("instructionSet == null");
14866            }
14867            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14868            for (String codePath : allCodePaths) {
14869                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14870                    try {
14871                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14872                    } catch (InstallerException ignored) {
14873                    }
14874                }
14875            }
14876        }
14877    }
14878
14879    /**
14880     * Logic to handle installation of non-ASEC applications, including copying
14881     * and renaming logic.
14882     */
14883    class FileInstallArgs extends InstallArgs {
14884        private File codeFile;
14885        private File resourceFile;
14886
14887        // Example topology:
14888        // /data/app/com.example/base.apk
14889        // /data/app/com.example/split_foo.apk
14890        // /data/app/com.example/lib/arm/libfoo.so
14891        // /data/app/com.example/lib/arm64/libfoo.so
14892        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14893
14894        /** New install */
14895        FileInstallArgs(InstallParams params) {
14896            super(params.origin, params.move, params.observer, params.installFlags,
14897                    params.installerPackageName, params.volumeUuid,
14898                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14899                    params.grantedRuntimePermissions,
14900                    params.traceMethod, params.traceCookie, params.certificates,
14901                    params.installReason);
14902            if (isFwdLocked()) {
14903                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14904            }
14905        }
14906
14907        /** Existing install */
14908        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14909            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14910                    null, null, null, 0, null /*certificates*/,
14911                    PackageManager.INSTALL_REASON_UNKNOWN);
14912            this.codeFile = (codePath != null) ? new File(codePath) : null;
14913            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14914        }
14915
14916        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14917            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14918            try {
14919                return doCopyApk(imcs, temp);
14920            } finally {
14921                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14922            }
14923        }
14924
14925        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14926            if (origin.staged) {
14927                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14928                codeFile = origin.file;
14929                resourceFile = origin.file;
14930                return PackageManager.INSTALL_SUCCEEDED;
14931            }
14932
14933            try {
14934                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14935                final File tempDir =
14936                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14937                codeFile = tempDir;
14938                resourceFile = tempDir;
14939            } catch (IOException e) {
14940                Slog.w(TAG, "Failed to create copy file: " + e);
14941                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14942            }
14943
14944            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14945                @Override
14946                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14947                    if (!FileUtils.isValidExtFilename(name)) {
14948                        throw new IllegalArgumentException("Invalid filename: " + name);
14949                    }
14950                    try {
14951                        final File file = new File(codeFile, name);
14952                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14953                                O_RDWR | O_CREAT, 0644);
14954                        Os.chmod(file.getAbsolutePath(), 0644);
14955                        return new ParcelFileDescriptor(fd);
14956                    } catch (ErrnoException e) {
14957                        throw new RemoteException("Failed to open: " + e.getMessage());
14958                    }
14959                }
14960            };
14961
14962            int ret = PackageManager.INSTALL_SUCCEEDED;
14963            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14964            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14965                Slog.e(TAG, "Failed to copy package");
14966                return ret;
14967            }
14968
14969            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14970            NativeLibraryHelper.Handle handle = null;
14971            try {
14972                handle = NativeLibraryHelper.Handle.create(codeFile);
14973                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14974                        abiOverride);
14975            } catch (IOException e) {
14976                Slog.e(TAG, "Copying native libraries failed", e);
14977                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14978            } finally {
14979                IoUtils.closeQuietly(handle);
14980            }
14981
14982            return ret;
14983        }
14984
14985        int doPreInstall(int status) {
14986            if (status != PackageManager.INSTALL_SUCCEEDED) {
14987                cleanUp();
14988            }
14989            return status;
14990        }
14991
14992        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14993            if (status != PackageManager.INSTALL_SUCCEEDED) {
14994                cleanUp();
14995                return false;
14996            }
14997
14998            final File targetDir = codeFile.getParentFile();
14999            final File beforeCodeFile = codeFile;
15000            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15001
15002            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15003            try {
15004                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15005            } catch (ErrnoException e) {
15006                Slog.w(TAG, "Failed to rename", e);
15007                return false;
15008            }
15009
15010            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15011                Slog.w(TAG, "Failed to restorecon");
15012                return false;
15013            }
15014
15015            // Reflect the rename internally
15016            codeFile = afterCodeFile;
15017            resourceFile = afterCodeFile;
15018
15019            // Reflect the rename in scanned details
15020            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15021            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15022                    afterCodeFile, pkg.baseCodePath));
15023            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15024                    afterCodeFile, pkg.splitCodePaths));
15025
15026            // Reflect the rename in app info
15027            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15028            pkg.setApplicationInfoCodePath(pkg.codePath);
15029            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15030            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15031            pkg.setApplicationInfoResourcePath(pkg.codePath);
15032            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15033            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15034
15035            return true;
15036        }
15037
15038        int doPostInstall(int status, int uid) {
15039            if (status != PackageManager.INSTALL_SUCCEEDED) {
15040                cleanUp();
15041            }
15042            return status;
15043        }
15044
15045        @Override
15046        String getCodePath() {
15047            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15048        }
15049
15050        @Override
15051        String getResourcePath() {
15052            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15053        }
15054
15055        private boolean cleanUp() {
15056            if (codeFile == null || !codeFile.exists()) {
15057                return false;
15058            }
15059
15060            removeCodePathLI(codeFile);
15061
15062            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15063                resourceFile.delete();
15064            }
15065
15066            return true;
15067        }
15068
15069        void cleanUpResourcesLI() {
15070            // Try enumerating all code paths before deleting
15071            List<String> allCodePaths = Collections.EMPTY_LIST;
15072            if (codeFile != null && codeFile.exists()) {
15073                try {
15074                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15075                    allCodePaths = pkg.getAllCodePaths();
15076                } catch (PackageParserException e) {
15077                    // Ignored; we tried our best
15078                }
15079            }
15080
15081            cleanUp();
15082            removeDexFiles(allCodePaths, instructionSets);
15083        }
15084
15085        boolean doPostDeleteLI(boolean delete) {
15086            // XXX err, shouldn't we respect the delete flag?
15087            cleanUpResourcesLI();
15088            return true;
15089        }
15090    }
15091
15092    private boolean isAsecExternal(String cid) {
15093        final String asecPath = PackageHelper.getSdFilesystem(cid);
15094        return !asecPath.startsWith(mAsecInternalPath);
15095    }
15096
15097    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15098            PackageManagerException {
15099        if (copyRet < 0) {
15100            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15101                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15102                throw new PackageManagerException(copyRet, message);
15103            }
15104        }
15105    }
15106
15107    /**
15108     * Extract the StorageManagerService "container ID" from the full code path of an
15109     * .apk.
15110     */
15111    static String cidFromCodePath(String fullCodePath) {
15112        int eidx = fullCodePath.lastIndexOf("/");
15113        String subStr1 = fullCodePath.substring(0, eidx);
15114        int sidx = subStr1.lastIndexOf("/");
15115        return subStr1.substring(sidx+1, eidx);
15116    }
15117
15118    /**
15119     * Logic to handle installation of ASEC applications, including copying and
15120     * renaming logic.
15121     */
15122    class AsecInstallArgs extends InstallArgs {
15123        static final String RES_FILE_NAME = "pkg.apk";
15124        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15125
15126        String cid;
15127        String packagePath;
15128        String resourcePath;
15129
15130        /** New install */
15131        AsecInstallArgs(InstallParams params) {
15132            super(params.origin, params.move, params.observer, params.installFlags,
15133                    params.installerPackageName, params.volumeUuid,
15134                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15135                    params.grantedRuntimePermissions,
15136                    params.traceMethod, params.traceCookie, params.certificates,
15137                    params.installReason);
15138        }
15139
15140        /** Existing install */
15141        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15142                        boolean isExternal, boolean isForwardLocked) {
15143            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15144                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15145                    instructionSets, null, null, null, 0, null /*certificates*/,
15146                    PackageManager.INSTALL_REASON_UNKNOWN);
15147            // Hackily pretend we're still looking at a full code path
15148            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15149                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15150            }
15151
15152            // Extract cid from fullCodePath
15153            int eidx = fullCodePath.lastIndexOf("/");
15154            String subStr1 = fullCodePath.substring(0, eidx);
15155            int sidx = subStr1.lastIndexOf("/");
15156            cid = subStr1.substring(sidx+1, eidx);
15157            setMountPath(subStr1);
15158        }
15159
15160        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15161            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15162                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15163                    instructionSets, null, null, null, 0, null /*certificates*/,
15164                    PackageManager.INSTALL_REASON_UNKNOWN);
15165            this.cid = cid;
15166            setMountPath(PackageHelper.getSdDir(cid));
15167        }
15168
15169        void createCopyFile() {
15170            cid = mInstallerService.allocateExternalStageCidLegacy();
15171        }
15172
15173        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15174            if (origin.staged && origin.cid != null) {
15175                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15176                cid = origin.cid;
15177                setMountPath(PackageHelper.getSdDir(cid));
15178                return PackageManager.INSTALL_SUCCEEDED;
15179            }
15180
15181            if (temp) {
15182                createCopyFile();
15183            } else {
15184                /*
15185                 * Pre-emptively destroy the container since it's destroyed if
15186                 * copying fails due to it existing anyway.
15187                 */
15188                PackageHelper.destroySdDir(cid);
15189            }
15190
15191            final String newMountPath = imcs.copyPackageToContainer(
15192                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15193                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15194
15195            if (newMountPath != null) {
15196                setMountPath(newMountPath);
15197                return PackageManager.INSTALL_SUCCEEDED;
15198            } else {
15199                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15200            }
15201        }
15202
15203        @Override
15204        String getCodePath() {
15205            return packagePath;
15206        }
15207
15208        @Override
15209        String getResourcePath() {
15210            return resourcePath;
15211        }
15212
15213        int doPreInstall(int status) {
15214            if (status != PackageManager.INSTALL_SUCCEEDED) {
15215                // Destroy container
15216                PackageHelper.destroySdDir(cid);
15217            } else {
15218                boolean mounted = PackageHelper.isContainerMounted(cid);
15219                if (!mounted) {
15220                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15221                            Process.SYSTEM_UID);
15222                    if (newMountPath != null) {
15223                        setMountPath(newMountPath);
15224                    } else {
15225                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15226                    }
15227                }
15228            }
15229            return status;
15230        }
15231
15232        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15233            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15234            String newMountPath = null;
15235            if (PackageHelper.isContainerMounted(cid)) {
15236                // Unmount the container
15237                if (!PackageHelper.unMountSdDir(cid)) {
15238                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15239                    return false;
15240                }
15241            }
15242            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15243                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15244                        " which might be stale. Will try to clean up.");
15245                // Clean up the stale container and proceed to recreate.
15246                if (!PackageHelper.destroySdDir(newCacheId)) {
15247                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15248                    return false;
15249                }
15250                // Successfully cleaned up stale container. Try to rename again.
15251                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15252                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15253                            + " inspite of cleaning it up.");
15254                    return false;
15255                }
15256            }
15257            if (!PackageHelper.isContainerMounted(newCacheId)) {
15258                Slog.w(TAG, "Mounting container " + newCacheId);
15259                newMountPath = PackageHelper.mountSdDir(newCacheId,
15260                        getEncryptKey(), Process.SYSTEM_UID);
15261            } else {
15262                newMountPath = PackageHelper.getSdDir(newCacheId);
15263            }
15264            if (newMountPath == null) {
15265                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15266                return false;
15267            }
15268            Log.i(TAG, "Succesfully renamed " + cid +
15269                    " to " + newCacheId +
15270                    " at new path: " + newMountPath);
15271            cid = newCacheId;
15272
15273            final File beforeCodeFile = new File(packagePath);
15274            setMountPath(newMountPath);
15275            final File afterCodeFile = new File(packagePath);
15276
15277            // Reflect the rename in scanned details
15278            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15279            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15280                    afterCodeFile, pkg.baseCodePath));
15281            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15282                    afterCodeFile, pkg.splitCodePaths));
15283
15284            // Reflect the rename in app info
15285            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15286            pkg.setApplicationInfoCodePath(pkg.codePath);
15287            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15288            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15289            pkg.setApplicationInfoResourcePath(pkg.codePath);
15290            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15291            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15292
15293            return true;
15294        }
15295
15296        private void setMountPath(String mountPath) {
15297            final File mountFile = new File(mountPath);
15298
15299            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15300            if (monolithicFile.exists()) {
15301                packagePath = monolithicFile.getAbsolutePath();
15302                if (isFwdLocked()) {
15303                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15304                } else {
15305                    resourcePath = packagePath;
15306                }
15307            } else {
15308                packagePath = mountFile.getAbsolutePath();
15309                resourcePath = packagePath;
15310            }
15311        }
15312
15313        int doPostInstall(int status, int uid) {
15314            if (status != PackageManager.INSTALL_SUCCEEDED) {
15315                cleanUp();
15316            } else {
15317                final int groupOwner;
15318                final String protectedFile;
15319                if (isFwdLocked()) {
15320                    groupOwner = UserHandle.getSharedAppGid(uid);
15321                    protectedFile = RES_FILE_NAME;
15322                } else {
15323                    groupOwner = -1;
15324                    protectedFile = null;
15325                }
15326
15327                if (uid < Process.FIRST_APPLICATION_UID
15328                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15329                    Slog.e(TAG, "Failed to finalize " + cid);
15330                    PackageHelper.destroySdDir(cid);
15331                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15332                }
15333
15334                boolean mounted = PackageHelper.isContainerMounted(cid);
15335                if (!mounted) {
15336                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15337                }
15338            }
15339            return status;
15340        }
15341
15342        private void cleanUp() {
15343            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15344
15345            // Destroy secure container
15346            PackageHelper.destroySdDir(cid);
15347        }
15348
15349        private List<String> getAllCodePaths() {
15350            final File codeFile = new File(getCodePath());
15351            if (codeFile != null && codeFile.exists()) {
15352                try {
15353                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15354                    return pkg.getAllCodePaths();
15355                } catch (PackageParserException e) {
15356                    // Ignored; we tried our best
15357                }
15358            }
15359            return Collections.EMPTY_LIST;
15360        }
15361
15362        void cleanUpResourcesLI() {
15363            // Enumerate all code paths before deleting
15364            cleanUpResourcesLI(getAllCodePaths());
15365        }
15366
15367        private void cleanUpResourcesLI(List<String> allCodePaths) {
15368            cleanUp();
15369            removeDexFiles(allCodePaths, instructionSets);
15370        }
15371
15372        String getPackageName() {
15373            return getAsecPackageName(cid);
15374        }
15375
15376        boolean doPostDeleteLI(boolean delete) {
15377            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15378            final List<String> allCodePaths = getAllCodePaths();
15379            boolean mounted = PackageHelper.isContainerMounted(cid);
15380            if (mounted) {
15381                // Unmount first
15382                if (PackageHelper.unMountSdDir(cid)) {
15383                    mounted = false;
15384                }
15385            }
15386            if (!mounted && delete) {
15387                cleanUpResourcesLI(allCodePaths);
15388            }
15389            return !mounted;
15390        }
15391
15392        @Override
15393        int doPreCopy() {
15394            if (isFwdLocked()) {
15395                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15396                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15397                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15398                }
15399            }
15400
15401            return PackageManager.INSTALL_SUCCEEDED;
15402        }
15403
15404        @Override
15405        int doPostCopy(int uid) {
15406            if (isFwdLocked()) {
15407                if (uid < Process.FIRST_APPLICATION_UID
15408                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15409                                RES_FILE_NAME)) {
15410                    Slog.e(TAG, "Failed to finalize " + cid);
15411                    PackageHelper.destroySdDir(cid);
15412                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15413                }
15414            }
15415
15416            return PackageManager.INSTALL_SUCCEEDED;
15417        }
15418    }
15419
15420    /**
15421     * Logic to handle movement of existing installed applications.
15422     */
15423    class MoveInstallArgs extends InstallArgs {
15424        private File codeFile;
15425        private File resourceFile;
15426
15427        /** New install */
15428        MoveInstallArgs(InstallParams params) {
15429            super(params.origin, params.move, params.observer, params.installFlags,
15430                    params.installerPackageName, params.volumeUuid,
15431                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15432                    params.grantedRuntimePermissions,
15433                    params.traceMethod, params.traceCookie, params.certificates,
15434                    params.installReason);
15435        }
15436
15437        int copyApk(IMediaContainerService imcs, boolean temp) {
15438            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15439                    + move.fromUuid + " to " + move.toUuid);
15440            synchronized (mInstaller) {
15441                try {
15442                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15443                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15444                } catch (InstallerException e) {
15445                    Slog.w(TAG, "Failed to move app", e);
15446                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15447                }
15448            }
15449
15450            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15451            resourceFile = codeFile;
15452            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15453
15454            return PackageManager.INSTALL_SUCCEEDED;
15455        }
15456
15457        int doPreInstall(int status) {
15458            if (status != PackageManager.INSTALL_SUCCEEDED) {
15459                cleanUp(move.toUuid);
15460            }
15461            return status;
15462        }
15463
15464        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15465            if (status != PackageManager.INSTALL_SUCCEEDED) {
15466                cleanUp(move.toUuid);
15467                return false;
15468            }
15469
15470            // Reflect the move in app info
15471            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15472            pkg.setApplicationInfoCodePath(pkg.codePath);
15473            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15474            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15475            pkg.setApplicationInfoResourcePath(pkg.codePath);
15476            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15477            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15478
15479            return true;
15480        }
15481
15482        int doPostInstall(int status, int uid) {
15483            if (status == PackageManager.INSTALL_SUCCEEDED) {
15484                cleanUp(move.fromUuid);
15485            } else {
15486                cleanUp(move.toUuid);
15487            }
15488            return status;
15489        }
15490
15491        @Override
15492        String getCodePath() {
15493            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15494        }
15495
15496        @Override
15497        String getResourcePath() {
15498            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15499        }
15500
15501        private boolean cleanUp(String volumeUuid) {
15502            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15503                    move.dataAppName);
15504            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15505            final int[] userIds = sUserManager.getUserIds();
15506            synchronized (mInstallLock) {
15507                // Clean up both app data and code
15508                // All package moves are frozen until finished
15509                for (int userId : userIds) {
15510                    try {
15511                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15512                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15513                    } catch (InstallerException e) {
15514                        Slog.w(TAG, String.valueOf(e));
15515                    }
15516                }
15517                removeCodePathLI(codeFile);
15518            }
15519            return true;
15520        }
15521
15522        void cleanUpResourcesLI() {
15523            throw new UnsupportedOperationException();
15524        }
15525
15526        boolean doPostDeleteLI(boolean delete) {
15527            throw new UnsupportedOperationException();
15528        }
15529    }
15530
15531    static String getAsecPackageName(String packageCid) {
15532        int idx = packageCid.lastIndexOf("-");
15533        if (idx == -1) {
15534            return packageCid;
15535        }
15536        return packageCid.substring(0, idx);
15537    }
15538
15539    // Utility method used to create code paths based on package name and available index.
15540    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15541        String idxStr = "";
15542        int idx = 1;
15543        // Fall back to default value of idx=1 if prefix is not
15544        // part of oldCodePath
15545        if (oldCodePath != null) {
15546            String subStr = oldCodePath;
15547            // Drop the suffix right away
15548            if (suffix != null && subStr.endsWith(suffix)) {
15549                subStr = subStr.substring(0, subStr.length() - suffix.length());
15550            }
15551            // If oldCodePath already contains prefix find out the
15552            // ending index to either increment or decrement.
15553            int sidx = subStr.lastIndexOf(prefix);
15554            if (sidx != -1) {
15555                subStr = subStr.substring(sidx + prefix.length());
15556                if (subStr != null) {
15557                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15558                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15559                    }
15560                    try {
15561                        idx = Integer.parseInt(subStr);
15562                        if (idx <= 1) {
15563                            idx++;
15564                        } else {
15565                            idx--;
15566                        }
15567                    } catch(NumberFormatException e) {
15568                    }
15569                }
15570            }
15571        }
15572        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15573        return prefix + idxStr;
15574    }
15575
15576    private File getNextCodePath(File targetDir, String packageName) {
15577        File result;
15578        SecureRandom random = new SecureRandom();
15579        byte[] bytes = new byte[16];
15580        do {
15581            random.nextBytes(bytes);
15582            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15583            result = new File(targetDir, packageName + "-" + suffix);
15584        } while (result.exists());
15585        return result;
15586    }
15587
15588    // Utility method that returns the relative package path with respect
15589    // to the installation directory. Like say for /data/data/com.test-1.apk
15590    // string com.test-1 is returned.
15591    static String deriveCodePathName(String codePath) {
15592        if (codePath == null) {
15593            return null;
15594        }
15595        final File codeFile = new File(codePath);
15596        final String name = codeFile.getName();
15597        if (codeFile.isDirectory()) {
15598            return name;
15599        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15600            final int lastDot = name.lastIndexOf('.');
15601            return name.substring(0, lastDot);
15602        } else {
15603            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15604            return null;
15605        }
15606    }
15607
15608    static class PackageInstalledInfo {
15609        String name;
15610        int uid;
15611        // The set of users that originally had this package installed.
15612        int[] origUsers;
15613        // The set of users that now have this package installed.
15614        int[] newUsers;
15615        PackageParser.Package pkg;
15616        int returnCode;
15617        String returnMsg;
15618        PackageRemovedInfo removedInfo;
15619        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15620
15621        public void setError(int code, String msg) {
15622            setReturnCode(code);
15623            setReturnMessage(msg);
15624            Slog.w(TAG, msg);
15625        }
15626
15627        public void setError(String msg, PackageParserException e) {
15628            setReturnCode(e.error);
15629            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15630            Slog.w(TAG, msg, e);
15631        }
15632
15633        public void setError(String msg, PackageManagerException e) {
15634            returnCode = e.error;
15635            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15636            Slog.w(TAG, msg, e);
15637        }
15638
15639        public void setReturnCode(int returnCode) {
15640            this.returnCode = returnCode;
15641            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15642            for (int i = 0; i < childCount; i++) {
15643                addedChildPackages.valueAt(i).returnCode = returnCode;
15644            }
15645        }
15646
15647        private void setReturnMessage(String returnMsg) {
15648            this.returnMsg = returnMsg;
15649            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15650            for (int i = 0; i < childCount; i++) {
15651                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15652            }
15653        }
15654
15655        // In some error cases we want to convey more info back to the observer
15656        String origPackage;
15657        String origPermission;
15658    }
15659
15660    /*
15661     * Install a non-existing package.
15662     */
15663    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15664            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15665            PackageInstalledInfo res, int installReason) {
15666        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15667
15668        // Remember this for later, in case we need to rollback this install
15669        String pkgName = pkg.packageName;
15670
15671        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15672
15673        synchronized(mPackages) {
15674            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15675            if (renamedPackage != null) {
15676                // A package with the same name is already installed, though
15677                // it has been renamed to an older name.  The package we
15678                // are trying to install should be installed as an update to
15679                // the existing one, but that has not been requested, so bail.
15680                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15681                        + " without first uninstalling package running as "
15682                        + renamedPackage);
15683                return;
15684            }
15685            if (mPackages.containsKey(pkgName)) {
15686                // Don't allow installation over an existing package with the same name.
15687                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15688                        + " without first uninstalling.");
15689                return;
15690            }
15691        }
15692
15693        try {
15694            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15695                    System.currentTimeMillis(), user);
15696
15697            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15698
15699            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15700                prepareAppDataAfterInstallLIF(newPackage);
15701
15702            } else {
15703                // Remove package from internal structures, but keep around any
15704                // data that might have already existed
15705                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15706                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15707            }
15708        } catch (PackageManagerException e) {
15709            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15710        }
15711
15712        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15713    }
15714
15715    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15716        // Can't rotate keys during boot or if sharedUser.
15717        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15718                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15719            return false;
15720        }
15721        // app is using upgradeKeySets; make sure all are valid
15722        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15723        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15724        for (int i = 0; i < upgradeKeySets.length; i++) {
15725            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15726                Slog.wtf(TAG, "Package "
15727                         + (oldPs.name != null ? oldPs.name : "<null>")
15728                         + " contains upgrade-key-set reference to unknown key-set: "
15729                         + upgradeKeySets[i]
15730                         + " reverting to signatures check.");
15731                return false;
15732            }
15733        }
15734        return true;
15735    }
15736
15737    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15738        // Upgrade keysets are being used.  Determine if new package has a superset of the
15739        // required keys.
15740        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15741        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15742        for (int i = 0; i < upgradeKeySets.length; i++) {
15743            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15744            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15745                return true;
15746            }
15747        }
15748        return false;
15749    }
15750
15751    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15752        try (DigestInputStream digestStream =
15753                new DigestInputStream(new FileInputStream(file), digest)) {
15754            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15755        }
15756    }
15757
15758    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15759            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15760            int installReason) {
15761        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15762
15763        final PackageParser.Package oldPackage;
15764        final String pkgName = pkg.packageName;
15765        final int[] allUsers;
15766        final int[] installedUsers;
15767
15768        synchronized(mPackages) {
15769            oldPackage = mPackages.get(pkgName);
15770            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15771
15772            // don't allow upgrade to target a release SDK from a pre-release SDK
15773            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15774                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15775            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15776                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15777            if (oldTargetsPreRelease
15778                    && !newTargetsPreRelease
15779                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15780                Slog.w(TAG, "Can't install package targeting released sdk");
15781                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15782                return;
15783            }
15784
15785            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15786
15787            // verify signatures are valid
15788            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15789                if (!checkUpgradeKeySetLP(ps, pkg)) {
15790                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15791                            "New package not signed by keys specified by upgrade-keysets: "
15792                                    + pkgName);
15793                    return;
15794                }
15795            } else {
15796                // default to original signature matching
15797                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15798                        != PackageManager.SIGNATURE_MATCH) {
15799                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15800                            "New package has a different signature: " + pkgName);
15801                    return;
15802                }
15803            }
15804
15805            // don't allow a system upgrade unless the upgrade hash matches
15806            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15807                byte[] digestBytes = null;
15808                try {
15809                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15810                    updateDigest(digest, new File(pkg.baseCodePath));
15811                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15812                        for (String path : pkg.splitCodePaths) {
15813                            updateDigest(digest, new File(path));
15814                        }
15815                    }
15816                    digestBytes = digest.digest();
15817                } catch (NoSuchAlgorithmException | IOException e) {
15818                    res.setError(INSTALL_FAILED_INVALID_APK,
15819                            "Could not compute hash: " + pkgName);
15820                    return;
15821                }
15822                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15823                    res.setError(INSTALL_FAILED_INVALID_APK,
15824                            "New package fails restrict-update check: " + pkgName);
15825                    return;
15826                }
15827                // retain upgrade restriction
15828                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15829            }
15830
15831            // Check for shared user id changes
15832            String invalidPackageName =
15833                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15834            if (invalidPackageName != null) {
15835                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15836                        "Package " + invalidPackageName + " tried to change user "
15837                                + oldPackage.mSharedUserId);
15838                return;
15839            }
15840
15841            // In case of rollback, remember per-user/profile install state
15842            allUsers = sUserManager.getUserIds();
15843            installedUsers = ps.queryInstalledUsers(allUsers, true);
15844
15845            // don't allow an upgrade from full to ephemeral
15846            if (isInstantApp) {
15847                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15848                    for (int currentUser : allUsers) {
15849                        if (!ps.getInstantApp(currentUser)) {
15850                            // can't downgrade from full to instant
15851                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15852                                    + " for user: " + currentUser);
15853                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15854                            return;
15855                        }
15856                    }
15857                } else if (!ps.getInstantApp(user.getIdentifier())) {
15858                    // can't downgrade from full to instant
15859                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15860                            + " for user: " + user.getIdentifier());
15861                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15862                    return;
15863                }
15864            }
15865        }
15866
15867        // Update what is removed
15868        res.removedInfo = new PackageRemovedInfo();
15869        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15870        res.removedInfo.removedPackage = oldPackage.packageName;
15871        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15872        res.removedInfo.isUpdate = true;
15873        res.removedInfo.origUsers = installedUsers;
15874        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15875        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15876        for (int i = 0; i < installedUsers.length; i++) {
15877            final int userId = installedUsers[i];
15878            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15879        }
15880
15881        final int childCount = (oldPackage.childPackages != null)
15882                ? oldPackage.childPackages.size() : 0;
15883        for (int i = 0; i < childCount; i++) {
15884            boolean childPackageUpdated = false;
15885            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15886            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15887            if (res.addedChildPackages != null) {
15888                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15889                if (childRes != null) {
15890                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15891                    childRes.removedInfo.removedPackage = childPkg.packageName;
15892                    childRes.removedInfo.isUpdate = true;
15893                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15894                    childPackageUpdated = true;
15895                }
15896            }
15897            if (!childPackageUpdated) {
15898                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15899                childRemovedRes.removedPackage = childPkg.packageName;
15900                childRemovedRes.isUpdate = false;
15901                childRemovedRes.dataRemoved = true;
15902                synchronized (mPackages) {
15903                    if (childPs != null) {
15904                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15905                    }
15906                }
15907                if (res.removedInfo.removedChildPackages == null) {
15908                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15909                }
15910                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15911            }
15912        }
15913
15914        boolean sysPkg = (isSystemApp(oldPackage));
15915        if (sysPkg) {
15916            // Set the system/privileged flags as needed
15917            final boolean privileged =
15918                    (oldPackage.applicationInfo.privateFlags
15919                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15920            final int systemPolicyFlags = policyFlags
15921                    | PackageParser.PARSE_IS_SYSTEM
15922                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15923
15924            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15925                    user, allUsers, installerPackageName, res, installReason);
15926        } else {
15927            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15928                    user, allUsers, installerPackageName, res, installReason);
15929        }
15930    }
15931
15932    public List<String> getPreviousCodePaths(String packageName) {
15933        final PackageSetting ps = mSettings.mPackages.get(packageName);
15934        final List<String> result = new ArrayList<String>();
15935        if (ps != null && ps.oldCodePaths != null) {
15936            result.addAll(ps.oldCodePaths);
15937        }
15938        return result;
15939    }
15940
15941    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15942            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15943            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15944            int installReason) {
15945        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15946                + deletedPackage);
15947
15948        String pkgName = deletedPackage.packageName;
15949        boolean deletedPkg = true;
15950        boolean addedPkg = false;
15951        boolean updatedSettings = false;
15952        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15953        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15954                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15955
15956        final long origUpdateTime = (pkg.mExtras != null)
15957                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15958
15959        // First delete the existing package while retaining the data directory
15960        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15961                res.removedInfo, true, pkg)) {
15962            // If the existing package wasn't successfully deleted
15963            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15964            deletedPkg = false;
15965        } else {
15966            // Successfully deleted the old package; proceed with replace.
15967
15968            // If deleted package lived in a container, give users a chance to
15969            // relinquish resources before killing.
15970            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15971                if (DEBUG_INSTALL) {
15972                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15973                }
15974                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15975                final ArrayList<String> pkgList = new ArrayList<String>(1);
15976                pkgList.add(deletedPackage.applicationInfo.packageName);
15977                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15978            }
15979
15980            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15981                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15982            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15983
15984            try {
15985                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15986                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15987                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15988                        installReason);
15989
15990                // Update the in-memory copy of the previous code paths.
15991                PackageSetting ps = mSettings.mPackages.get(pkgName);
15992                if (!killApp) {
15993                    if (ps.oldCodePaths == null) {
15994                        ps.oldCodePaths = new ArraySet<>();
15995                    }
15996                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15997                    if (deletedPackage.splitCodePaths != null) {
15998                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15999                    }
16000                } else {
16001                    ps.oldCodePaths = null;
16002                }
16003                if (ps.childPackageNames != null) {
16004                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16005                        final String childPkgName = ps.childPackageNames.get(i);
16006                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16007                        childPs.oldCodePaths = ps.oldCodePaths;
16008                    }
16009                }
16010                // set instant app status, but, only if it's explicitly specified
16011                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16012                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16013                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16014                prepareAppDataAfterInstallLIF(newPackage);
16015                addedPkg = true;
16016                mDexManager.notifyPackageUpdated(newPackage.packageName,
16017                        newPackage.baseCodePath, newPackage.splitCodePaths);
16018            } catch (PackageManagerException e) {
16019                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16020            }
16021        }
16022
16023        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16024            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16025
16026            // Revert all internal state mutations and added folders for the failed install
16027            if (addedPkg) {
16028                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16029                        res.removedInfo, true, null);
16030            }
16031
16032            // Restore the old package
16033            if (deletedPkg) {
16034                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16035                File restoreFile = new File(deletedPackage.codePath);
16036                // Parse old package
16037                boolean oldExternal = isExternal(deletedPackage);
16038                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16039                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16040                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16041                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16042                try {
16043                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16044                            null);
16045                } catch (PackageManagerException e) {
16046                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16047                            + e.getMessage());
16048                    return;
16049                }
16050
16051                synchronized (mPackages) {
16052                    // Ensure the installer package name up to date
16053                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16054
16055                    // Update permissions for restored package
16056                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16057
16058                    mSettings.writeLPr();
16059                }
16060
16061                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16062            }
16063        } else {
16064            synchronized (mPackages) {
16065                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16066                if (ps != null) {
16067                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16068                    if (res.removedInfo.removedChildPackages != null) {
16069                        final int childCount = res.removedInfo.removedChildPackages.size();
16070                        // Iterate in reverse as we may modify the collection
16071                        for (int i = childCount - 1; i >= 0; i--) {
16072                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16073                            if (res.addedChildPackages.containsKey(childPackageName)) {
16074                                res.removedInfo.removedChildPackages.removeAt(i);
16075                            } else {
16076                                PackageRemovedInfo childInfo = res.removedInfo
16077                                        .removedChildPackages.valueAt(i);
16078                                childInfo.removedForAllUsers = mPackages.get(
16079                                        childInfo.removedPackage) == null;
16080                            }
16081                        }
16082                    }
16083                }
16084            }
16085        }
16086    }
16087
16088    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16089            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16090            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16091            int installReason) {
16092        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16093                + ", old=" + deletedPackage);
16094
16095        final boolean disabledSystem;
16096
16097        // Remove existing system package
16098        removePackageLI(deletedPackage, true);
16099
16100        synchronized (mPackages) {
16101            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16102        }
16103        if (!disabledSystem) {
16104            // We didn't need to disable the .apk as a current system package,
16105            // which means we are replacing another update that is already
16106            // installed.  We need to make sure to delete the older one's .apk.
16107            res.removedInfo.args = createInstallArgsForExisting(0,
16108                    deletedPackage.applicationInfo.getCodePath(),
16109                    deletedPackage.applicationInfo.getResourcePath(),
16110                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16111        } else {
16112            res.removedInfo.args = null;
16113        }
16114
16115        // Successfully disabled the old package. Now proceed with re-installation
16116        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16117                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16118        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16119
16120        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16121        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16122                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16123
16124        PackageParser.Package newPackage = null;
16125        try {
16126            // Add the package to the internal data structures
16127            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16128
16129            // Set the update and install times
16130            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16131            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16132                    System.currentTimeMillis());
16133
16134            // Update the package dynamic state if succeeded
16135            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16136                // Now that the install succeeded make sure we remove data
16137                // directories for any child package the update removed.
16138                final int deletedChildCount = (deletedPackage.childPackages != null)
16139                        ? deletedPackage.childPackages.size() : 0;
16140                final int newChildCount = (newPackage.childPackages != null)
16141                        ? newPackage.childPackages.size() : 0;
16142                for (int i = 0; i < deletedChildCount; i++) {
16143                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16144                    boolean childPackageDeleted = true;
16145                    for (int j = 0; j < newChildCount; j++) {
16146                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16147                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16148                            childPackageDeleted = false;
16149                            break;
16150                        }
16151                    }
16152                    if (childPackageDeleted) {
16153                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16154                                deletedChildPkg.packageName);
16155                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16156                            PackageRemovedInfo removedChildRes = res.removedInfo
16157                                    .removedChildPackages.get(deletedChildPkg.packageName);
16158                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16159                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16160                        }
16161                    }
16162                }
16163
16164                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16165                        installReason);
16166                prepareAppDataAfterInstallLIF(newPackage);
16167
16168                mDexManager.notifyPackageUpdated(newPackage.packageName,
16169                            newPackage.baseCodePath, newPackage.splitCodePaths);
16170            }
16171        } catch (PackageManagerException e) {
16172            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16173            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16174        }
16175
16176        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16177            // Re installation failed. Restore old information
16178            // Remove new pkg information
16179            if (newPackage != null) {
16180                removeInstalledPackageLI(newPackage, true);
16181            }
16182            // Add back the old system package
16183            try {
16184                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16185            } catch (PackageManagerException e) {
16186                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16187            }
16188
16189            synchronized (mPackages) {
16190                if (disabledSystem) {
16191                    enableSystemPackageLPw(deletedPackage);
16192                }
16193
16194                // Ensure the installer package name up to date
16195                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16196
16197                // Update permissions for restored package
16198                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16199
16200                mSettings.writeLPr();
16201            }
16202
16203            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16204                    + " after failed upgrade");
16205        }
16206    }
16207
16208    /**
16209     * Checks whether the parent or any of the child packages have a change shared
16210     * user. For a package to be a valid update the shred users of the parent and
16211     * the children should match. We may later support changing child shared users.
16212     * @param oldPkg The updated package.
16213     * @param newPkg The update package.
16214     * @return The shared user that change between the versions.
16215     */
16216    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16217            PackageParser.Package newPkg) {
16218        // Check parent shared user
16219        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16220            return newPkg.packageName;
16221        }
16222        // Check child shared users
16223        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16224        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16225        for (int i = 0; i < newChildCount; i++) {
16226            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16227            // If this child was present, did it have the same shared user?
16228            for (int j = 0; j < oldChildCount; j++) {
16229                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16230                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16231                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16232                    return newChildPkg.packageName;
16233                }
16234            }
16235        }
16236        return null;
16237    }
16238
16239    private void removeNativeBinariesLI(PackageSetting ps) {
16240        // Remove the lib path for the parent package
16241        if (ps != null) {
16242            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16243            // Remove the lib path for the child packages
16244            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16245            for (int i = 0; i < childCount; i++) {
16246                PackageSetting childPs = null;
16247                synchronized (mPackages) {
16248                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16249                }
16250                if (childPs != null) {
16251                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16252                            .legacyNativeLibraryPathString);
16253                }
16254            }
16255        }
16256    }
16257
16258    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16259        // Enable the parent package
16260        mSettings.enableSystemPackageLPw(pkg.packageName);
16261        // Enable the child packages
16262        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16263        for (int i = 0; i < childCount; i++) {
16264            PackageParser.Package childPkg = pkg.childPackages.get(i);
16265            mSettings.enableSystemPackageLPw(childPkg.packageName);
16266        }
16267    }
16268
16269    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16270            PackageParser.Package newPkg) {
16271        // Disable the parent package (parent always replaced)
16272        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16273        // Disable the child packages
16274        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16275        for (int i = 0; i < childCount; i++) {
16276            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16277            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16278            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16279        }
16280        return disabled;
16281    }
16282
16283    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16284            String installerPackageName) {
16285        // Enable the parent package
16286        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16287        // Enable the child packages
16288        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16289        for (int i = 0; i < childCount; i++) {
16290            PackageParser.Package childPkg = pkg.childPackages.get(i);
16291            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16292        }
16293    }
16294
16295    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16296        // Collect all used permissions in the UID
16297        ArraySet<String> usedPermissions = new ArraySet<>();
16298        final int packageCount = su.packages.size();
16299        for (int i = 0; i < packageCount; i++) {
16300            PackageSetting ps = su.packages.valueAt(i);
16301            if (ps.pkg == null) {
16302                continue;
16303            }
16304            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16305            for (int j = 0; j < requestedPermCount; j++) {
16306                String permission = ps.pkg.requestedPermissions.get(j);
16307                BasePermission bp = mSettings.mPermissions.get(permission);
16308                if (bp != null) {
16309                    usedPermissions.add(permission);
16310                }
16311            }
16312        }
16313
16314        PermissionsState permissionsState = su.getPermissionsState();
16315        // Prune install permissions
16316        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16317        final int installPermCount = installPermStates.size();
16318        for (int i = installPermCount - 1; i >= 0;  i--) {
16319            PermissionState permissionState = installPermStates.get(i);
16320            if (!usedPermissions.contains(permissionState.getName())) {
16321                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16322                if (bp != null) {
16323                    permissionsState.revokeInstallPermission(bp);
16324                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16325                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16326                }
16327            }
16328        }
16329
16330        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16331
16332        // Prune runtime permissions
16333        for (int userId : allUserIds) {
16334            List<PermissionState> runtimePermStates = permissionsState
16335                    .getRuntimePermissionStates(userId);
16336            final int runtimePermCount = runtimePermStates.size();
16337            for (int i = runtimePermCount - 1; i >= 0; i--) {
16338                PermissionState permissionState = runtimePermStates.get(i);
16339                if (!usedPermissions.contains(permissionState.getName())) {
16340                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16341                    if (bp != null) {
16342                        permissionsState.revokeRuntimePermission(bp, userId);
16343                        permissionsState.updatePermissionFlags(bp, userId,
16344                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16345                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16346                                runtimePermissionChangedUserIds, userId);
16347                    }
16348                }
16349            }
16350        }
16351
16352        return runtimePermissionChangedUserIds;
16353    }
16354
16355    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16356            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16357        // Update the parent package setting
16358        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16359                res, user, installReason);
16360        // Update the child packages setting
16361        final int childCount = (newPackage.childPackages != null)
16362                ? newPackage.childPackages.size() : 0;
16363        for (int i = 0; i < childCount; i++) {
16364            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16365            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16366            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16367                    childRes.origUsers, childRes, user, installReason);
16368        }
16369    }
16370
16371    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16372            String installerPackageName, int[] allUsers, int[] installedForUsers,
16373            PackageInstalledInfo res, UserHandle user, int installReason) {
16374        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16375
16376        String pkgName = newPackage.packageName;
16377        synchronized (mPackages) {
16378            //write settings. the installStatus will be incomplete at this stage.
16379            //note that the new package setting would have already been
16380            //added to mPackages. It hasn't been persisted yet.
16381            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16382            // TODO: Remove this write? It's also written at the end of this method
16383            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16384            mSettings.writeLPr();
16385            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16386        }
16387
16388        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16389        synchronized (mPackages) {
16390            updatePermissionsLPw(newPackage.packageName, newPackage,
16391                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16392                            ? UPDATE_PERMISSIONS_ALL : 0));
16393            // For system-bundled packages, we assume that installing an upgraded version
16394            // of the package implies that the user actually wants to run that new code,
16395            // so we enable the package.
16396            PackageSetting ps = mSettings.mPackages.get(pkgName);
16397            final int userId = user.getIdentifier();
16398            if (ps != null) {
16399                if (isSystemApp(newPackage)) {
16400                    if (DEBUG_INSTALL) {
16401                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16402                    }
16403                    // Enable system package for requested users
16404                    if (res.origUsers != null) {
16405                        for (int origUserId : res.origUsers) {
16406                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16407                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16408                                        origUserId, installerPackageName);
16409                            }
16410                        }
16411                    }
16412                    // Also convey the prior install/uninstall state
16413                    if (allUsers != null && installedForUsers != null) {
16414                        for (int currentUserId : allUsers) {
16415                            final boolean installed = ArrayUtils.contains(
16416                                    installedForUsers, currentUserId);
16417                            if (DEBUG_INSTALL) {
16418                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16419                            }
16420                            ps.setInstalled(installed, currentUserId);
16421                        }
16422                        // these install state changes will be persisted in the
16423                        // upcoming call to mSettings.writeLPr().
16424                    }
16425                }
16426                // It's implied that when a user requests installation, they want the app to be
16427                // installed and enabled.
16428                if (userId != UserHandle.USER_ALL) {
16429                    ps.setInstalled(true, userId);
16430                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16431                }
16432
16433                // When replacing an existing package, preserve the original install reason for all
16434                // users that had the package installed before.
16435                final Set<Integer> previousUserIds = new ArraySet<>();
16436                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16437                    final int installReasonCount = res.removedInfo.installReasons.size();
16438                    for (int i = 0; i < installReasonCount; i++) {
16439                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16440                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16441                        ps.setInstallReason(previousInstallReason, previousUserId);
16442                        previousUserIds.add(previousUserId);
16443                    }
16444                }
16445
16446                // Set install reason for users that are having the package newly installed.
16447                if (userId == UserHandle.USER_ALL) {
16448                    for (int currentUserId : sUserManager.getUserIds()) {
16449                        if (!previousUserIds.contains(currentUserId)) {
16450                            ps.setInstallReason(installReason, currentUserId);
16451                        }
16452                    }
16453                } else if (!previousUserIds.contains(userId)) {
16454                    ps.setInstallReason(installReason, userId);
16455                }
16456                mSettings.writeKernelMappingLPr(ps);
16457            }
16458            res.name = pkgName;
16459            res.uid = newPackage.applicationInfo.uid;
16460            res.pkg = newPackage;
16461            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16462            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16463            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16464            //to update install status
16465            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16466            mSettings.writeLPr();
16467            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16468        }
16469
16470        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16471    }
16472
16473    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16474        try {
16475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16476            installPackageLI(args, res);
16477        } finally {
16478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16479        }
16480    }
16481
16482    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16483        final int installFlags = args.installFlags;
16484        final String installerPackageName = args.installerPackageName;
16485        final String volumeUuid = args.volumeUuid;
16486        final File tmpPackageFile = new File(args.getCodePath());
16487        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16488        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16489                || (args.volumeUuid != null));
16490        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16491        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16492        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16493        boolean replace = false;
16494        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16495        if (args.move != null) {
16496            // moving a complete application; perform an initial scan on the new install location
16497            scanFlags |= SCAN_INITIAL;
16498        }
16499        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16500            scanFlags |= SCAN_DONT_KILL_APP;
16501        }
16502        if (instantApp) {
16503            scanFlags |= SCAN_AS_INSTANT_APP;
16504        }
16505        if (fullApp) {
16506            scanFlags |= SCAN_AS_FULL_APP;
16507        }
16508
16509        // Result object to be returned
16510        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16511
16512        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16513
16514        // Sanity check
16515        if (instantApp && (forwardLocked || onExternal)) {
16516            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16517                    + " external=" + onExternal);
16518            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16519            return;
16520        }
16521
16522        // Retrieve PackageSettings and parse package
16523        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16524                | PackageParser.PARSE_ENFORCE_CODE
16525                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16526                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16527                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16528                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16529        PackageParser pp = new PackageParser();
16530        pp.setSeparateProcesses(mSeparateProcesses);
16531        pp.setDisplayMetrics(mMetrics);
16532        pp.setCallback(mPackageParserCallback);
16533
16534        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16535        final PackageParser.Package pkg;
16536        try {
16537            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16538        } catch (PackageParserException e) {
16539            res.setError("Failed parse during installPackageLI", e);
16540            return;
16541        } finally {
16542            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16543        }
16544
16545        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16546        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16547            Slog.w(TAG, "Instant app package " + pkg.packageName
16548                    + " does not target O, this will be a fatal error.");
16549            // STOPSHIP: Make this a fatal error
16550            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16551        }
16552        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16553            Slog.w(TAG, "Instant app package " + pkg.packageName
16554                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16555            // STOPSHIP: Make this a fatal error
16556            pkg.applicationInfo.targetSandboxVersion = 2;
16557        }
16558
16559        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16560            // Static shared libraries have synthetic package names
16561            renameStaticSharedLibraryPackage(pkg);
16562
16563            // No static shared libs on external storage
16564            if (onExternal) {
16565                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16566                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16567                        "Packages declaring static-shared libs cannot be updated");
16568                return;
16569            }
16570        }
16571
16572        // If we are installing a clustered package add results for the children
16573        if (pkg.childPackages != null) {
16574            synchronized (mPackages) {
16575                final int childCount = pkg.childPackages.size();
16576                for (int i = 0; i < childCount; i++) {
16577                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16578                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16579                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16580                    childRes.pkg = childPkg;
16581                    childRes.name = childPkg.packageName;
16582                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16583                    if (childPs != null) {
16584                        childRes.origUsers = childPs.queryInstalledUsers(
16585                                sUserManager.getUserIds(), true);
16586                    }
16587                    if ((mPackages.containsKey(childPkg.packageName))) {
16588                        childRes.removedInfo = new PackageRemovedInfo();
16589                        childRes.removedInfo.removedPackage = childPkg.packageName;
16590                    }
16591                    if (res.addedChildPackages == null) {
16592                        res.addedChildPackages = new ArrayMap<>();
16593                    }
16594                    res.addedChildPackages.put(childPkg.packageName, childRes);
16595                }
16596            }
16597        }
16598
16599        // If package doesn't declare API override, mark that we have an install
16600        // time CPU ABI override.
16601        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16602            pkg.cpuAbiOverride = args.abiOverride;
16603        }
16604
16605        String pkgName = res.name = pkg.packageName;
16606        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16607            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16608                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16609                return;
16610            }
16611        }
16612
16613        try {
16614            // either use what we've been given or parse directly from the APK
16615            if (args.certificates != null) {
16616                try {
16617                    PackageParser.populateCertificates(pkg, args.certificates);
16618                } catch (PackageParserException e) {
16619                    // there was something wrong with the certificates we were given;
16620                    // try to pull them from the APK
16621                    PackageParser.collectCertificates(pkg, parseFlags);
16622                }
16623            } else {
16624                PackageParser.collectCertificates(pkg, parseFlags);
16625            }
16626        } catch (PackageParserException e) {
16627            res.setError("Failed collect during installPackageLI", e);
16628            return;
16629        }
16630
16631        // Get rid of all references to package scan path via parser.
16632        pp = null;
16633        String oldCodePath = null;
16634        boolean systemApp = false;
16635        synchronized (mPackages) {
16636            // Check if installing already existing package
16637            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16638                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16639                if (pkg.mOriginalPackages != null
16640                        && pkg.mOriginalPackages.contains(oldName)
16641                        && mPackages.containsKey(oldName)) {
16642                    // This package is derived from an original package,
16643                    // and this device has been updating from that original
16644                    // name.  We must continue using the original name, so
16645                    // rename the new package here.
16646                    pkg.setPackageName(oldName);
16647                    pkgName = pkg.packageName;
16648                    replace = true;
16649                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16650                            + oldName + " pkgName=" + pkgName);
16651                } else if (mPackages.containsKey(pkgName)) {
16652                    // This package, under its official name, already exists
16653                    // on the device; we should replace it.
16654                    replace = true;
16655                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16656                }
16657
16658                // Child packages are installed through the parent package
16659                if (pkg.parentPackage != null) {
16660                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16661                            "Package " + pkg.packageName + " is child of package "
16662                                    + pkg.parentPackage.parentPackage + ". Child packages "
16663                                    + "can be updated only through the parent package.");
16664                    return;
16665                }
16666
16667                if (replace) {
16668                    // Prevent apps opting out from runtime permissions
16669                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16670                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16671                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16672                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16673                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16674                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16675                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16676                                        + " doesn't support runtime permissions but the old"
16677                                        + " target SDK " + oldTargetSdk + " does.");
16678                        return;
16679                    }
16680                    // Prevent apps from downgrading their targetSandbox.
16681                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16682                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16683                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16684                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16685                                "Package " + pkg.packageName + " new target sandbox "
16686                                + newTargetSandbox + " is incompatible with the previous value of"
16687                                + oldTargetSandbox + ".");
16688                        return;
16689                    }
16690
16691                    // Prevent installing of child packages
16692                    if (oldPackage.parentPackage != null) {
16693                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16694                                "Package " + pkg.packageName + " is child of package "
16695                                        + oldPackage.parentPackage + ". Child packages "
16696                                        + "can be updated only through the parent package.");
16697                        return;
16698                    }
16699                }
16700            }
16701
16702            PackageSetting ps = mSettings.mPackages.get(pkgName);
16703            if (ps != null) {
16704                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16705
16706                // Static shared libs have same package with different versions where
16707                // we internally use a synthetic package name to allow multiple versions
16708                // of the same package, therefore we need to compare signatures against
16709                // the package setting for the latest library version.
16710                PackageSetting signatureCheckPs = ps;
16711                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16712                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16713                    if (libraryEntry != null) {
16714                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16715                    }
16716                }
16717
16718                // Quick sanity check that we're signed correctly if updating;
16719                // we'll check this again later when scanning, but we want to
16720                // bail early here before tripping over redefined permissions.
16721                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16722                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16723                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16724                                + pkg.packageName + " upgrade keys do not match the "
16725                                + "previously installed version");
16726                        return;
16727                    }
16728                } else {
16729                    try {
16730                        verifySignaturesLP(signatureCheckPs, pkg);
16731                    } catch (PackageManagerException e) {
16732                        res.setError(e.error, e.getMessage());
16733                        return;
16734                    }
16735                }
16736
16737                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16738                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16739                    systemApp = (ps.pkg.applicationInfo.flags &
16740                            ApplicationInfo.FLAG_SYSTEM) != 0;
16741                }
16742                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16743            }
16744
16745            int N = pkg.permissions.size();
16746            for (int i = N-1; i >= 0; i--) {
16747                PackageParser.Permission perm = pkg.permissions.get(i);
16748                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16749
16750                // Don't allow anyone but the platform to define ephemeral permissions.
16751                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16752                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16753                    Slog.w(TAG, "Package " + pkg.packageName
16754                            + " attempting to delcare ephemeral permission "
16755                            + perm.info.name + "; Removing ephemeral.");
16756                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16757                }
16758                // Check whether the newly-scanned package wants to define an already-defined perm
16759                if (bp != null) {
16760                    // If the defining package is signed with our cert, it's okay.  This
16761                    // also includes the "updating the same package" case, of course.
16762                    // "updating same package" could also involve key-rotation.
16763                    final boolean sigsOk;
16764                    if (bp.sourcePackage.equals(pkg.packageName)
16765                            && (bp.packageSetting instanceof PackageSetting)
16766                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16767                                    scanFlags))) {
16768                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16769                    } else {
16770                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16771                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16772                    }
16773                    if (!sigsOk) {
16774                        // If the owning package is the system itself, we log but allow
16775                        // install to proceed; we fail the install on all other permission
16776                        // redefinitions.
16777                        if (!bp.sourcePackage.equals("android")) {
16778                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16779                                    + pkg.packageName + " attempting to redeclare permission "
16780                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16781                            res.origPermission = perm.info.name;
16782                            res.origPackage = bp.sourcePackage;
16783                            return;
16784                        } else {
16785                            Slog.w(TAG, "Package " + pkg.packageName
16786                                    + " attempting to redeclare system permission "
16787                                    + perm.info.name + "; ignoring new declaration");
16788                            pkg.permissions.remove(i);
16789                        }
16790                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16791                        // Prevent apps to change protection level to dangerous from any other
16792                        // type as this would allow a privilege escalation where an app adds a
16793                        // normal/signature permission in other app's group and later redefines
16794                        // it as dangerous leading to the group auto-grant.
16795                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16796                                == PermissionInfo.PROTECTION_DANGEROUS) {
16797                            if (bp != null && !bp.isRuntime()) {
16798                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16799                                        + "non-runtime permission " + perm.info.name
16800                                        + " to runtime; keeping old protection level");
16801                                perm.info.protectionLevel = bp.protectionLevel;
16802                            }
16803                        }
16804                    }
16805                }
16806            }
16807        }
16808
16809        if (systemApp) {
16810            if (onExternal) {
16811                // Abort update; system app can't be replaced with app on sdcard
16812                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16813                        "Cannot install updates to system apps on sdcard");
16814                return;
16815            } else if (instantApp) {
16816                // Abort update; system app can't be replaced with an instant app
16817                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16818                        "Cannot update a system app with an instant app");
16819                return;
16820            }
16821        }
16822
16823        if (args.move != null) {
16824            // We did an in-place move, so dex is ready to roll
16825            scanFlags |= SCAN_NO_DEX;
16826            scanFlags |= SCAN_MOVE;
16827
16828            synchronized (mPackages) {
16829                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16830                if (ps == null) {
16831                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16832                            "Missing settings for moved package " + pkgName);
16833                }
16834
16835                // We moved the entire application as-is, so bring over the
16836                // previously derived ABI information.
16837                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16838                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16839            }
16840
16841        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16842            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16843            scanFlags |= SCAN_NO_DEX;
16844
16845            try {
16846                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16847                    args.abiOverride : pkg.cpuAbiOverride);
16848                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16849                        true /*extractLibs*/, mAppLib32InstallDir);
16850            } catch (PackageManagerException pme) {
16851                Slog.e(TAG, "Error deriving application ABI", pme);
16852                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16853                return;
16854            }
16855
16856            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16857            // Do not run PackageDexOptimizer through the local performDexOpt
16858            // method because `pkg` may not be in `mPackages` yet.
16859            //
16860            // Also, don't fail application installs if the dexopt step fails.
16861            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16862                    null /* instructionSets */, false /* checkProfiles */,
16863                    getCompilerFilterForReason(REASON_INSTALL),
16864                    getOrCreateCompilerPackageStats(pkg),
16865                    mDexManager.isUsedByOtherApps(pkg.packageName));
16866            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16867
16868            // Notify BackgroundDexOptService that the package has been changed.
16869            // If this is an update of a package which used to fail to compile,
16870            // BDOS will remove it from its blacklist.
16871            // TODO: Layering violation
16872            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16873        }
16874
16875        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16876            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16877            return;
16878        }
16879
16880        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16881
16882        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16883                "installPackageLI")) {
16884            if (replace) {
16885                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16886                    // Static libs have a synthetic package name containing the version
16887                    // and cannot be updated as an update would get a new package name,
16888                    // unless this is the exact same version code which is useful for
16889                    // development.
16890                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16891                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16892                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16893                                + "static-shared libs cannot be updated");
16894                        return;
16895                    }
16896                }
16897                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16898                        installerPackageName, res, args.installReason);
16899            } else {
16900                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16901                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16902            }
16903        }
16904        synchronized (mPackages) {
16905            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16906            if (ps != null) {
16907                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16908                ps.setUpdateAvailable(false /*updateAvailable*/);
16909            }
16910
16911            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16912            for (int i = 0; i < childCount; i++) {
16913                PackageParser.Package childPkg = pkg.childPackages.get(i);
16914                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16915                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16916                if (childPs != null) {
16917                    childRes.newUsers = childPs.queryInstalledUsers(
16918                            sUserManager.getUserIds(), true);
16919                }
16920            }
16921
16922            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16923                updateSequenceNumberLP(pkgName, res.newUsers);
16924                updateInstantAppInstallerLocked();
16925            }
16926        }
16927    }
16928
16929    private void startIntentFilterVerifications(int userId, boolean replacing,
16930            PackageParser.Package pkg) {
16931        if (mIntentFilterVerifierComponent == null) {
16932            Slog.w(TAG, "No IntentFilter verification will not be done as "
16933                    + "there is no IntentFilterVerifier available!");
16934            return;
16935        }
16936
16937        final int verifierUid = getPackageUid(
16938                mIntentFilterVerifierComponent.getPackageName(),
16939                MATCH_DEBUG_TRIAGED_MISSING,
16940                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16941
16942        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16943        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16944        mHandler.sendMessage(msg);
16945
16946        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16947        for (int i = 0; i < childCount; i++) {
16948            PackageParser.Package childPkg = pkg.childPackages.get(i);
16949            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16950            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16951            mHandler.sendMessage(msg);
16952        }
16953    }
16954
16955    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16956            PackageParser.Package pkg) {
16957        int size = pkg.activities.size();
16958        if (size == 0) {
16959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16960                    "No activity, so no need to verify any IntentFilter!");
16961            return;
16962        }
16963
16964        final boolean hasDomainURLs = hasDomainURLs(pkg);
16965        if (!hasDomainURLs) {
16966            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16967                    "No domain URLs, so no need to verify any IntentFilter!");
16968            return;
16969        }
16970
16971        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16972                + " if any IntentFilter from the " + size
16973                + " Activities needs verification ...");
16974
16975        int count = 0;
16976        final String packageName = pkg.packageName;
16977
16978        synchronized (mPackages) {
16979            // If this is a new install and we see that we've already run verification for this
16980            // package, we have nothing to do: it means the state was restored from backup.
16981            if (!replacing) {
16982                IntentFilterVerificationInfo ivi =
16983                        mSettings.getIntentFilterVerificationLPr(packageName);
16984                if (ivi != null) {
16985                    if (DEBUG_DOMAIN_VERIFICATION) {
16986                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16987                                + ivi.getStatusString());
16988                    }
16989                    return;
16990                }
16991            }
16992
16993            // If any filters need to be verified, then all need to be.
16994            boolean needToVerify = false;
16995            for (PackageParser.Activity a : pkg.activities) {
16996                for (ActivityIntentInfo filter : a.intents) {
16997                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16998                        if (DEBUG_DOMAIN_VERIFICATION) {
16999                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17000                        }
17001                        needToVerify = true;
17002                        break;
17003                    }
17004                }
17005            }
17006
17007            if (needToVerify) {
17008                final int verificationId = mIntentFilterVerificationToken++;
17009                for (PackageParser.Activity a : pkg.activities) {
17010                    for (ActivityIntentInfo filter : a.intents) {
17011                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17012                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17013                                    "Verification needed for IntentFilter:" + filter.toString());
17014                            mIntentFilterVerifier.addOneIntentFilterVerification(
17015                                    verifierUid, userId, verificationId, filter, packageName);
17016                            count++;
17017                        }
17018                    }
17019                }
17020            }
17021        }
17022
17023        if (count > 0) {
17024            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17025                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17026                    +  " for userId:" + userId);
17027            mIntentFilterVerifier.startVerifications(userId);
17028        } else {
17029            if (DEBUG_DOMAIN_VERIFICATION) {
17030                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17031            }
17032        }
17033    }
17034
17035    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17036        final ComponentName cn  = filter.activity.getComponentName();
17037        final String packageName = cn.getPackageName();
17038
17039        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17040                packageName);
17041        if (ivi == null) {
17042            return true;
17043        }
17044        int status = ivi.getStatus();
17045        switch (status) {
17046            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17047            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17048                return true;
17049
17050            default:
17051                // Nothing to do
17052                return false;
17053        }
17054    }
17055
17056    private static boolean isMultiArch(ApplicationInfo info) {
17057        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17058    }
17059
17060    private static boolean isExternal(PackageParser.Package pkg) {
17061        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17062    }
17063
17064    private static boolean isExternal(PackageSetting ps) {
17065        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17066    }
17067
17068    private static boolean isSystemApp(PackageParser.Package pkg) {
17069        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17070    }
17071
17072    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17073        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17074    }
17075
17076    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17077        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17078    }
17079
17080    private static boolean isSystemApp(PackageSetting ps) {
17081        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17082    }
17083
17084    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17085        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17086    }
17087
17088    private int packageFlagsToInstallFlags(PackageSetting ps) {
17089        int installFlags = 0;
17090        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17091            // This existing package was an external ASEC install when we have
17092            // the external flag without a UUID
17093            installFlags |= PackageManager.INSTALL_EXTERNAL;
17094        }
17095        if (ps.isForwardLocked()) {
17096            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17097        }
17098        return installFlags;
17099    }
17100
17101    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17102        if (isExternal(pkg)) {
17103            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17104                return StorageManager.UUID_PRIMARY_PHYSICAL;
17105            } else {
17106                return pkg.volumeUuid;
17107            }
17108        } else {
17109            return StorageManager.UUID_PRIVATE_INTERNAL;
17110        }
17111    }
17112
17113    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17114        if (isExternal(pkg)) {
17115            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17116                return mSettings.getExternalVersion();
17117            } else {
17118                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17119            }
17120        } else {
17121            return mSettings.getInternalVersion();
17122        }
17123    }
17124
17125    private void deleteTempPackageFiles() {
17126        final FilenameFilter filter = new FilenameFilter() {
17127            public boolean accept(File dir, String name) {
17128                return name.startsWith("vmdl") && name.endsWith(".tmp");
17129            }
17130        };
17131        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17132            file.delete();
17133        }
17134    }
17135
17136    @Override
17137    public void deletePackageAsUser(String packageName, int versionCode,
17138            IPackageDeleteObserver observer, int userId, int flags) {
17139        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17140                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17141    }
17142
17143    @Override
17144    public void deletePackageVersioned(VersionedPackage versionedPackage,
17145            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17146        mContext.enforceCallingOrSelfPermission(
17147                android.Manifest.permission.DELETE_PACKAGES, null);
17148        Preconditions.checkNotNull(versionedPackage);
17149        Preconditions.checkNotNull(observer);
17150        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17151                PackageManager.VERSION_CODE_HIGHEST,
17152                Integer.MAX_VALUE, "versionCode must be >= -1");
17153
17154        final String packageName = versionedPackage.getPackageName();
17155        // TODO: We will change version code to long, so in the new API it is long
17156        final int versionCode = (int) versionedPackage.getVersionCode();
17157        final String internalPackageName;
17158        synchronized (mPackages) {
17159            // Normalize package name to handle renamed packages and static libs
17160            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17161                    // TODO: We will change version code to long, so in the new API it is long
17162                    (int) versionedPackage.getVersionCode());
17163        }
17164
17165        final int uid = Binder.getCallingUid();
17166        if (!isOrphaned(internalPackageName)
17167                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17168            try {
17169                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17170                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17171                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17172                observer.onUserActionRequired(intent);
17173            } catch (RemoteException re) {
17174            }
17175            return;
17176        }
17177        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17178        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17179        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17180            mContext.enforceCallingOrSelfPermission(
17181                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17182                    "deletePackage for user " + userId);
17183        }
17184
17185        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17186            try {
17187                observer.onPackageDeleted(packageName,
17188                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17189            } catch (RemoteException re) {
17190            }
17191            return;
17192        }
17193
17194        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17195            try {
17196                observer.onPackageDeleted(packageName,
17197                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17198            } catch (RemoteException re) {
17199            }
17200            return;
17201        }
17202
17203        if (DEBUG_REMOVE) {
17204            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17205                    + " deleteAllUsers: " + deleteAllUsers + " version="
17206                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17207                    ? "VERSION_CODE_HIGHEST" : versionCode));
17208        }
17209        // Queue up an async operation since the package deletion may take a little while.
17210        mHandler.post(new Runnable() {
17211            public void run() {
17212                mHandler.removeCallbacks(this);
17213                int returnCode;
17214                if (!deleteAllUsers) {
17215                    returnCode = deletePackageX(internalPackageName, versionCode,
17216                            userId, deleteFlags);
17217                } else {
17218                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17219                            internalPackageName, users);
17220                    // If nobody is blocking uninstall, proceed with delete for all users
17221                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17222                        returnCode = deletePackageX(internalPackageName, versionCode,
17223                                userId, deleteFlags);
17224                    } else {
17225                        // Otherwise uninstall individually for users with blockUninstalls=false
17226                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17227                        for (int userId : users) {
17228                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17229                                returnCode = deletePackageX(internalPackageName, versionCode,
17230                                        userId, userFlags);
17231                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17232                                    Slog.w(TAG, "Package delete failed for user " + userId
17233                                            + ", returnCode " + returnCode);
17234                                }
17235                            }
17236                        }
17237                        // The app has only been marked uninstalled for certain users.
17238                        // We still need to report that delete was blocked
17239                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17240                    }
17241                }
17242                try {
17243                    observer.onPackageDeleted(packageName, returnCode, null);
17244                } catch (RemoteException e) {
17245                    Log.i(TAG, "Observer no longer exists.");
17246                } //end catch
17247            } //end run
17248        });
17249    }
17250
17251    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17252        if (pkg.staticSharedLibName != null) {
17253            return pkg.manifestPackageName;
17254        }
17255        return pkg.packageName;
17256    }
17257
17258    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17259        // Handle renamed packages
17260        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17261        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17262
17263        // Is this a static library?
17264        SparseArray<SharedLibraryEntry> versionedLib =
17265                mStaticLibsByDeclaringPackage.get(packageName);
17266        if (versionedLib == null || versionedLib.size() <= 0) {
17267            return packageName;
17268        }
17269
17270        // Figure out which lib versions the caller can see
17271        SparseIntArray versionsCallerCanSee = null;
17272        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17273        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17274                && callingAppId != Process.ROOT_UID) {
17275            versionsCallerCanSee = new SparseIntArray();
17276            String libName = versionedLib.valueAt(0).info.getName();
17277            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17278            if (uidPackages != null) {
17279                for (String uidPackage : uidPackages) {
17280                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17281                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17282                    if (libIdx >= 0) {
17283                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17284                        versionsCallerCanSee.append(libVersion, libVersion);
17285                    }
17286                }
17287            }
17288        }
17289
17290        // Caller can see nothing - done
17291        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17292            return packageName;
17293        }
17294
17295        // Find the version the caller can see and the app version code
17296        SharedLibraryEntry highestVersion = null;
17297        final int versionCount = versionedLib.size();
17298        for (int i = 0; i < versionCount; i++) {
17299            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17300            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17301                    libEntry.info.getVersion()) < 0) {
17302                continue;
17303            }
17304            // TODO: We will change version code to long, so in the new API it is long
17305            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17306            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17307                if (libVersionCode == versionCode) {
17308                    return libEntry.apk;
17309                }
17310            } else if (highestVersion == null) {
17311                highestVersion = libEntry;
17312            } else if (libVersionCode  > highestVersion.info
17313                    .getDeclaringPackage().getVersionCode()) {
17314                highestVersion = libEntry;
17315            }
17316        }
17317
17318        if (highestVersion != null) {
17319            return highestVersion.apk;
17320        }
17321
17322        return packageName;
17323    }
17324
17325    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17326        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17327              || callingUid == Process.SYSTEM_UID) {
17328            return true;
17329        }
17330        final int callingUserId = UserHandle.getUserId(callingUid);
17331        // If the caller installed the pkgName, then allow it to silently uninstall.
17332        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17333            return true;
17334        }
17335
17336        // Allow package verifier to silently uninstall.
17337        if (mRequiredVerifierPackage != null &&
17338                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17339            return true;
17340        }
17341
17342        // Allow package uninstaller to silently uninstall.
17343        if (mRequiredUninstallerPackage != null &&
17344                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17345            return true;
17346        }
17347
17348        // Allow storage manager to silently uninstall.
17349        if (mStorageManagerPackage != null &&
17350                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17351            return true;
17352        }
17353        return false;
17354    }
17355
17356    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17357        int[] result = EMPTY_INT_ARRAY;
17358        for (int userId : userIds) {
17359            if (getBlockUninstallForUser(packageName, userId)) {
17360                result = ArrayUtils.appendInt(result, userId);
17361            }
17362        }
17363        return result;
17364    }
17365
17366    @Override
17367    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17368        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17369    }
17370
17371    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17372        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17373                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17374        try {
17375            if (dpm != null) {
17376                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17377                        /* callingUserOnly =*/ false);
17378                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17379                        : deviceOwnerComponentName.getPackageName();
17380                // Does the package contains the device owner?
17381                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17382                // this check is probably not needed, since DO should be registered as a device
17383                // admin on some user too. (Original bug for this: b/17657954)
17384                if (packageName.equals(deviceOwnerPackageName)) {
17385                    return true;
17386                }
17387                // Does it contain a device admin for any user?
17388                int[] users;
17389                if (userId == UserHandle.USER_ALL) {
17390                    users = sUserManager.getUserIds();
17391                } else {
17392                    users = new int[]{userId};
17393                }
17394                for (int i = 0; i < users.length; ++i) {
17395                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17396                        return true;
17397                    }
17398                }
17399            }
17400        } catch (RemoteException e) {
17401        }
17402        return false;
17403    }
17404
17405    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17406        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17407    }
17408
17409    /**
17410     *  This method is an internal method that could be get invoked either
17411     *  to delete an installed package or to clean up a failed installation.
17412     *  After deleting an installed package, a broadcast is sent to notify any
17413     *  listeners that the package has been removed. For cleaning up a failed
17414     *  installation, the broadcast is not necessary since the package's
17415     *  installation wouldn't have sent the initial broadcast either
17416     *  The key steps in deleting a package are
17417     *  deleting the package information in internal structures like mPackages,
17418     *  deleting the packages base directories through installd
17419     *  updating mSettings to reflect current status
17420     *  persisting settings for later use
17421     *  sending a broadcast if necessary
17422     */
17423    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17424        final PackageRemovedInfo info = new PackageRemovedInfo();
17425        final boolean res;
17426
17427        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17428                ? UserHandle.USER_ALL : userId;
17429
17430        if (isPackageDeviceAdmin(packageName, removeUser)) {
17431            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17432            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17433        }
17434
17435        PackageSetting uninstalledPs = null;
17436        PackageParser.Package pkg = null;
17437
17438        // for the uninstall-updates case and restricted profiles, remember the per-
17439        // user handle installed state
17440        int[] allUsers;
17441        synchronized (mPackages) {
17442            uninstalledPs = mSettings.mPackages.get(packageName);
17443            if (uninstalledPs == null) {
17444                Slog.w(TAG, "Not removing non-existent package " + packageName);
17445                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17446            }
17447
17448            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17449                    && uninstalledPs.versionCode != versionCode) {
17450                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17451                        + uninstalledPs.versionCode + " != " + versionCode);
17452                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17453            }
17454
17455            // Static shared libs can be declared by any package, so let us not
17456            // allow removing a package if it provides a lib others depend on.
17457            pkg = mPackages.get(packageName);
17458            if (pkg != null && pkg.staticSharedLibName != null) {
17459                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17460                        pkg.staticSharedLibVersion);
17461                if (libEntry != null) {
17462                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17463                            libEntry.info, 0, userId);
17464                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17465                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17466                                + " hosting lib " + libEntry.info.getName() + " version "
17467                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17468                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17469                    }
17470                }
17471            }
17472
17473            allUsers = sUserManager.getUserIds();
17474            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17475        }
17476
17477        final int freezeUser;
17478        if (isUpdatedSystemApp(uninstalledPs)
17479                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17480            // We're downgrading a system app, which will apply to all users, so
17481            // freeze them all during the downgrade
17482            freezeUser = UserHandle.USER_ALL;
17483        } else {
17484            freezeUser = removeUser;
17485        }
17486
17487        synchronized (mInstallLock) {
17488            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17489            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17490                    deleteFlags, "deletePackageX")) {
17491                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17492                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17493            }
17494            synchronized (mPackages) {
17495                if (res) {
17496                    if (pkg != null) {
17497                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17498                    }
17499                    updateSequenceNumberLP(packageName, info.removedUsers);
17500                    updateInstantAppInstallerLocked();
17501                }
17502            }
17503        }
17504
17505        if (res) {
17506            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17507            info.sendPackageRemovedBroadcasts(killApp);
17508            info.sendSystemPackageUpdatedBroadcasts();
17509            info.sendSystemPackageAppearedBroadcasts();
17510        }
17511        // Force a gc here.
17512        Runtime.getRuntime().gc();
17513        // Delete the resources here after sending the broadcast to let
17514        // other processes clean up before deleting resources.
17515        if (info.args != null) {
17516            synchronized (mInstallLock) {
17517                info.args.doPostDeleteLI(true);
17518            }
17519        }
17520
17521        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17522    }
17523
17524    class PackageRemovedInfo {
17525        String removedPackage;
17526        int uid = -1;
17527        int removedAppId = -1;
17528        int[] origUsers;
17529        int[] removedUsers = null;
17530        SparseArray<Integer> installReasons;
17531        boolean isRemovedPackageSystemUpdate = false;
17532        boolean isUpdate;
17533        boolean dataRemoved;
17534        boolean removedForAllUsers;
17535        boolean isStaticSharedLib;
17536        // Clean up resources deleted packages.
17537        InstallArgs args = null;
17538        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17539        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17540
17541        void sendPackageRemovedBroadcasts(boolean killApp) {
17542            sendPackageRemovedBroadcastInternal(killApp);
17543            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17544            for (int i = 0; i < childCount; i++) {
17545                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17546                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17547            }
17548        }
17549
17550        void sendSystemPackageUpdatedBroadcasts() {
17551            if (isRemovedPackageSystemUpdate) {
17552                sendSystemPackageUpdatedBroadcastsInternal();
17553                final int childCount = (removedChildPackages != null)
17554                        ? removedChildPackages.size() : 0;
17555                for (int i = 0; i < childCount; i++) {
17556                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17557                    if (childInfo.isRemovedPackageSystemUpdate) {
17558                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17559                    }
17560                }
17561            }
17562        }
17563
17564        void sendSystemPackageAppearedBroadcasts() {
17565            final int packageCount = (appearedChildPackages != null)
17566                    ? appearedChildPackages.size() : 0;
17567            for (int i = 0; i < packageCount; i++) {
17568                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17569                sendPackageAddedForNewUsers(installedInfo.name, true,
17570                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17571            }
17572        }
17573
17574        private void sendSystemPackageUpdatedBroadcastsInternal() {
17575            Bundle extras = new Bundle(2);
17576            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17577            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17578            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17579                    extras, 0, null, null, null);
17580            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17581                    extras, 0, null, null, null);
17582            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17583                    null, 0, removedPackage, null, null);
17584        }
17585
17586        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17587            // Don't send static shared library removal broadcasts as these
17588            // libs are visible only the the apps that depend on them an one
17589            // cannot remove the library if it has a dependency.
17590            if (isStaticSharedLib) {
17591                return;
17592            }
17593            Bundle extras = new Bundle(2);
17594            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17595            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17596            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17597            if (isUpdate || isRemovedPackageSystemUpdate) {
17598                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17599            }
17600            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17601            if (removedPackage != null) {
17602                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17603                        extras, 0, null, null, removedUsers);
17604                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17605                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17606                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17607                            null, null, removedUsers);
17608                }
17609            }
17610            if (removedAppId >= 0) {
17611                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17612                        removedUsers);
17613            }
17614        }
17615    }
17616
17617    /*
17618     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17619     * flag is not set, the data directory is removed as well.
17620     * make sure this flag is set for partially installed apps. If not its meaningless to
17621     * delete a partially installed application.
17622     */
17623    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17624            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17625        String packageName = ps.name;
17626        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17627        // Retrieve object to delete permissions for shared user later on
17628        final PackageParser.Package deletedPkg;
17629        final PackageSetting deletedPs;
17630        // reader
17631        synchronized (mPackages) {
17632            deletedPkg = mPackages.get(packageName);
17633            deletedPs = mSettings.mPackages.get(packageName);
17634            if (outInfo != null) {
17635                outInfo.removedPackage = packageName;
17636                outInfo.isStaticSharedLib = deletedPkg != null
17637                        && deletedPkg.staticSharedLibName != null;
17638                outInfo.removedUsers = deletedPs != null
17639                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17640                        : null;
17641            }
17642        }
17643
17644        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17645
17646        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17647            final PackageParser.Package resolvedPkg;
17648            if (deletedPkg != null) {
17649                resolvedPkg = deletedPkg;
17650            } else {
17651                // We don't have a parsed package when it lives on an ejected
17652                // adopted storage device, so fake something together
17653                resolvedPkg = new PackageParser.Package(ps.name);
17654                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17655            }
17656            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17657                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17658            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17659            if (outInfo != null) {
17660                outInfo.dataRemoved = true;
17661            }
17662            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17663        }
17664
17665        int removedAppId = -1;
17666
17667        // writer
17668        synchronized (mPackages) {
17669            boolean installedStateChanged = false;
17670            if (deletedPs != null) {
17671                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17672                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17673                    clearDefaultBrowserIfNeeded(packageName);
17674                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17675                    removedAppId = mSettings.removePackageLPw(packageName);
17676                    if (outInfo != null) {
17677                        outInfo.removedAppId = removedAppId;
17678                    }
17679                    updatePermissionsLPw(deletedPs.name, null, 0);
17680                    if (deletedPs.sharedUser != null) {
17681                        // Remove permissions associated with package. Since runtime
17682                        // permissions are per user we have to kill the removed package
17683                        // or packages running under the shared user of the removed
17684                        // package if revoking the permissions requested only by the removed
17685                        // package is successful and this causes a change in gids.
17686                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17687                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17688                                    userId);
17689                            if (userIdToKill == UserHandle.USER_ALL
17690                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17691                                // If gids changed for this user, kill all affected packages.
17692                                mHandler.post(new Runnable() {
17693                                    @Override
17694                                    public void run() {
17695                                        // This has to happen with no lock held.
17696                                        killApplication(deletedPs.name, deletedPs.appId,
17697                                                KILL_APP_REASON_GIDS_CHANGED);
17698                                    }
17699                                });
17700                                break;
17701                            }
17702                        }
17703                    }
17704                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17705                }
17706                // make sure to preserve per-user disabled state if this removal was just
17707                // a downgrade of a system app to the factory package
17708                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17709                    if (DEBUG_REMOVE) {
17710                        Slog.d(TAG, "Propagating install state across downgrade");
17711                    }
17712                    for (int userId : allUserHandles) {
17713                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17714                        if (DEBUG_REMOVE) {
17715                            Slog.d(TAG, "    user " + userId + " => " + installed);
17716                        }
17717                        if (installed != ps.getInstalled(userId)) {
17718                            installedStateChanged = true;
17719                        }
17720                        ps.setInstalled(installed, userId);
17721                    }
17722                }
17723            }
17724            // can downgrade to reader
17725            if (writeSettings) {
17726                // Save settings now
17727                mSettings.writeLPr();
17728            }
17729            if (installedStateChanged) {
17730                mSettings.writeKernelMappingLPr(ps);
17731            }
17732        }
17733        if (removedAppId != -1) {
17734            // A user ID was deleted here. Go through all users and remove it
17735            // from KeyStore.
17736            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17737        }
17738    }
17739
17740    static boolean locationIsPrivileged(File path) {
17741        try {
17742            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17743                    .getCanonicalPath();
17744            return path.getCanonicalPath().startsWith(privilegedAppDir);
17745        } catch (IOException e) {
17746            Slog.e(TAG, "Unable to access code path " + path);
17747        }
17748        return false;
17749    }
17750
17751    /*
17752     * Tries to delete system package.
17753     */
17754    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17755            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17756            boolean writeSettings) {
17757        if (deletedPs.parentPackageName != null) {
17758            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17759            return false;
17760        }
17761
17762        final boolean applyUserRestrictions
17763                = (allUserHandles != null) && (outInfo.origUsers != null);
17764        final PackageSetting disabledPs;
17765        // Confirm if the system package has been updated
17766        // An updated system app can be deleted. This will also have to restore
17767        // the system pkg from system partition
17768        // reader
17769        synchronized (mPackages) {
17770            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17771        }
17772
17773        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17774                + " disabledPs=" + disabledPs);
17775
17776        if (disabledPs == null) {
17777            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17778            return false;
17779        } else if (DEBUG_REMOVE) {
17780            Slog.d(TAG, "Deleting system pkg from data partition");
17781        }
17782
17783        if (DEBUG_REMOVE) {
17784            if (applyUserRestrictions) {
17785                Slog.d(TAG, "Remembering install states:");
17786                for (int userId : allUserHandles) {
17787                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17788                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17789                }
17790            }
17791        }
17792
17793        // Delete the updated package
17794        outInfo.isRemovedPackageSystemUpdate = true;
17795        if (outInfo.removedChildPackages != null) {
17796            final int childCount = (deletedPs.childPackageNames != null)
17797                    ? deletedPs.childPackageNames.size() : 0;
17798            for (int i = 0; i < childCount; i++) {
17799                String childPackageName = deletedPs.childPackageNames.get(i);
17800                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17801                        .contains(childPackageName)) {
17802                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17803                            childPackageName);
17804                    if (childInfo != null) {
17805                        childInfo.isRemovedPackageSystemUpdate = true;
17806                    }
17807                }
17808            }
17809        }
17810
17811        if (disabledPs.versionCode < deletedPs.versionCode) {
17812            // Delete data for downgrades
17813            flags &= ~PackageManager.DELETE_KEEP_DATA;
17814        } else {
17815            // Preserve data by setting flag
17816            flags |= PackageManager.DELETE_KEEP_DATA;
17817        }
17818
17819        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17820                outInfo, writeSettings, disabledPs.pkg);
17821        if (!ret) {
17822            return false;
17823        }
17824
17825        // writer
17826        synchronized (mPackages) {
17827            // Reinstate the old system package
17828            enableSystemPackageLPw(disabledPs.pkg);
17829            // Remove any native libraries from the upgraded package.
17830            removeNativeBinariesLI(deletedPs);
17831        }
17832
17833        // Install the system package
17834        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17835        int parseFlags = mDefParseFlags
17836                | PackageParser.PARSE_MUST_BE_APK
17837                | PackageParser.PARSE_IS_SYSTEM
17838                | PackageParser.PARSE_IS_SYSTEM_DIR;
17839        if (locationIsPrivileged(disabledPs.codePath)) {
17840            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17841        }
17842
17843        final PackageParser.Package newPkg;
17844        try {
17845            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17846                0 /* currentTime */, null);
17847        } catch (PackageManagerException e) {
17848            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17849                    + e.getMessage());
17850            return false;
17851        }
17852
17853        try {
17854            // update shared libraries for the newly re-installed system package
17855            updateSharedLibrariesLPr(newPkg, null);
17856        } catch (PackageManagerException e) {
17857            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17858        }
17859
17860        prepareAppDataAfterInstallLIF(newPkg);
17861
17862        // writer
17863        synchronized (mPackages) {
17864            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17865
17866            // Propagate the permissions state as we do not want to drop on the floor
17867            // runtime permissions. The update permissions method below will take
17868            // care of removing obsolete permissions and grant install permissions.
17869            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17870            updatePermissionsLPw(newPkg.packageName, newPkg,
17871                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17872
17873            if (applyUserRestrictions) {
17874                boolean installedStateChanged = false;
17875                if (DEBUG_REMOVE) {
17876                    Slog.d(TAG, "Propagating install state across reinstall");
17877                }
17878                for (int userId : allUserHandles) {
17879                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17880                    if (DEBUG_REMOVE) {
17881                        Slog.d(TAG, "    user " + userId + " => " + installed);
17882                    }
17883                    if (installed != ps.getInstalled(userId)) {
17884                        installedStateChanged = true;
17885                    }
17886                    ps.setInstalled(installed, userId);
17887
17888                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17889                }
17890                // Regardless of writeSettings we need to ensure that this restriction
17891                // state propagation is persisted
17892                mSettings.writeAllUsersPackageRestrictionsLPr();
17893                if (installedStateChanged) {
17894                    mSettings.writeKernelMappingLPr(ps);
17895                }
17896            }
17897            // can downgrade to reader here
17898            if (writeSettings) {
17899                mSettings.writeLPr();
17900            }
17901        }
17902        return true;
17903    }
17904
17905    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17906            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17907            PackageRemovedInfo outInfo, boolean writeSettings,
17908            PackageParser.Package replacingPackage) {
17909        synchronized (mPackages) {
17910            if (outInfo != null) {
17911                outInfo.uid = ps.appId;
17912            }
17913
17914            if (outInfo != null && outInfo.removedChildPackages != null) {
17915                final int childCount = (ps.childPackageNames != null)
17916                        ? ps.childPackageNames.size() : 0;
17917                for (int i = 0; i < childCount; i++) {
17918                    String childPackageName = ps.childPackageNames.get(i);
17919                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17920                    if (childPs == null) {
17921                        return false;
17922                    }
17923                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17924                            childPackageName);
17925                    if (childInfo != null) {
17926                        childInfo.uid = childPs.appId;
17927                    }
17928                }
17929            }
17930        }
17931
17932        // Delete package data from internal structures and also remove data if flag is set
17933        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17934
17935        // Delete the child packages data
17936        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17937        for (int i = 0; i < childCount; i++) {
17938            PackageSetting childPs;
17939            synchronized (mPackages) {
17940                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17941            }
17942            if (childPs != null) {
17943                PackageRemovedInfo childOutInfo = (outInfo != null
17944                        && outInfo.removedChildPackages != null)
17945                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17946                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17947                        && (replacingPackage != null
17948                        && !replacingPackage.hasChildPackage(childPs.name))
17949                        ? flags & ~DELETE_KEEP_DATA : flags;
17950                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17951                        deleteFlags, writeSettings);
17952            }
17953        }
17954
17955        // Delete application code and resources only for parent packages
17956        if (ps.parentPackageName == null) {
17957            if (deleteCodeAndResources && (outInfo != null)) {
17958                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17959                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17960                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17961            }
17962        }
17963
17964        return true;
17965    }
17966
17967    @Override
17968    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17969            int userId) {
17970        mContext.enforceCallingOrSelfPermission(
17971                android.Manifest.permission.DELETE_PACKAGES, null);
17972        synchronized (mPackages) {
17973            PackageSetting ps = mSettings.mPackages.get(packageName);
17974            if (ps == null) {
17975                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17976                return false;
17977            }
17978            // Cannot block uninstall of static shared libs as they are
17979            // considered a part of the using app (emulating static linking).
17980            // Also static libs are installed always on internal storage.
17981            PackageParser.Package pkg = mPackages.get(packageName);
17982            if (pkg != null && pkg.staticSharedLibName != null) {
17983                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17984                        + " providing static shared library: " + pkg.staticSharedLibName);
17985                return false;
17986            }
17987            if (!ps.getInstalled(userId)) {
17988                // Can't block uninstall for an app that is not installed or enabled.
17989                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17990                return false;
17991            }
17992            ps.setBlockUninstall(blockUninstall, userId);
17993            mSettings.writePackageRestrictionsLPr(userId);
17994        }
17995        return true;
17996    }
17997
17998    @Override
17999    public boolean getBlockUninstallForUser(String packageName, int userId) {
18000        synchronized (mPackages) {
18001            PackageSetting ps = mSettings.mPackages.get(packageName);
18002            if (ps == null) {
18003                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18004                return false;
18005            }
18006            return ps.getBlockUninstall(userId);
18007        }
18008    }
18009
18010    @Override
18011    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18012        int callingUid = Binder.getCallingUid();
18013        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18014            throw new SecurityException(
18015                    "setRequiredForSystemUser can only be run by the system or root");
18016        }
18017        synchronized (mPackages) {
18018            PackageSetting ps = mSettings.mPackages.get(packageName);
18019            if (ps == null) {
18020                Log.w(TAG, "Package doesn't exist: " + packageName);
18021                return false;
18022            }
18023            if (systemUserApp) {
18024                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18025            } else {
18026                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18027            }
18028            mSettings.writeLPr();
18029        }
18030        return true;
18031    }
18032
18033    /*
18034     * This method handles package deletion in general
18035     */
18036    private boolean deletePackageLIF(String packageName, UserHandle user,
18037            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18038            PackageRemovedInfo outInfo, boolean writeSettings,
18039            PackageParser.Package replacingPackage) {
18040        if (packageName == null) {
18041            Slog.w(TAG, "Attempt to delete null packageName.");
18042            return false;
18043        }
18044
18045        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18046
18047        PackageSetting ps;
18048        synchronized (mPackages) {
18049            ps = mSettings.mPackages.get(packageName);
18050            if (ps == null) {
18051                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18052                return false;
18053            }
18054
18055            if (ps.parentPackageName != null && (!isSystemApp(ps)
18056                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18057                if (DEBUG_REMOVE) {
18058                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18059                            + ((user == null) ? UserHandle.USER_ALL : user));
18060                }
18061                final int removedUserId = (user != null) ? user.getIdentifier()
18062                        : UserHandle.USER_ALL;
18063                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18064                    return false;
18065                }
18066                markPackageUninstalledForUserLPw(ps, user);
18067                scheduleWritePackageRestrictionsLocked(user);
18068                return true;
18069            }
18070        }
18071
18072        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18073                && user.getIdentifier() != UserHandle.USER_ALL)) {
18074            // The caller is asking that the package only be deleted for a single
18075            // user.  To do this, we just mark its uninstalled state and delete
18076            // its data. If this is a system app, we only allow this to happen if
18077            // they have set the special DELETE_SYSTEM_APP which requests different
18078            // semantics than normal for uninstalling system apps.
18079            markPackageUninstalledForUserLPw(ps, user);
18080
18081            if (!isSystemApp(ps)) {
18082                // Do not uninstall the APK if an app should be cached
18083                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18084                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18085                    // Other user still have this package installed, so all
18086                    // we need to do is clear this user's data and save that
18087                    // it is uninstalled.
18088                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18089                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18090                        return false;
18091                    }
18092                    scheduleWritePackageRestrictionsLocked(user);
18093                    return true;
18094                } else {
18095                    // We need to set it back to 'installed' so the uninstall
18096                    // broadcasts will be sent correctly.
18097                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18098                    ps.setInstalled(true, user.getIdentifier());
18099                    mSettings.writeKernelMappingLPr(ps);
18100                }
18101            } else {
18102                // This is a system app, so we assume that the
18103                // other users still have this package installed, so all
18104                // we need to do is clear this user's data and save that
18105                // it is uninstalled.
18106                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18107                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18108                    return false;
18109                }
18110                scheduleWritePackageRestrictionsLocked(user);
18111                return true;
18112            }
18113        }
18114
18115        // If we are deleting a composite package for all users, keep track
18116        // of result for each child.
18117        if (ps.childPackageNames != null && outInfo != null) {
18118            synchronized (mPackages) {
18119                final int childCount = ps.childPackageNames.size();
18120                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18121                for (int i = 0; i < childCount; i++) {
18122                    String childPackageName = ps.childPackageNames.get(i);
18123                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18124                    childInfo.removedPackage = childPackageName;
18125                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18126                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18127                    if (childPs != null) {
18128                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18129                    }
18130                }
18131            }
18132        }
18133
18134        boolean ret = false;
18135        if (isSystemApp(ps)) {
18136            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18137            // When an updated system application is deleted we delete the existing resources
18138            // as well and fall back to existing code in system partition
18139            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18140        } else {
18141            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18142            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18143                    outInfo, writeSettings, replacingPackage);
18144        }
18145
18146        // Take a note whether we deleted the package for all users
18147        if (outInfo != null) {
18148            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18149            if (outInfo.removedChildPackages != null) {
18150                synchronized (mPackages) {
18151                    final int childCount = outInfo.removedChildPackages.size();
18152                    for (int i = 0; i < childCount; i++) {
18153                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18154                        if (childInfo != null) {
18155                            childInfo.removedForAllUsers = mPackages.get(
18156                                    childInfo.removedPackage) == null;
18157                        }
18158                    }
18159                }
18160            }
18161            // If we uninstalled an update to a system app there may be some
18162            // child packages that appeared as they are declared in the system
18163            // app but were not declared in the update.
18164            if (isSystemApp(ps)) {
18165                synchronized (mPackages) {
18166                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18167                    final int childCount = (updatedPs.childPackageNames != null)
18168                            ? updatedPs.childPackageNames.size() : 0;
18169                    for (int i = 0; i < childCount; i++) {
18170                        String childPackageName = updatedPs.childPackageNames.get(i);
18171                        if (outInfo.removedChildPackages == null
18172                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18173                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18174                            if (childPs == null) {
18175                                continue;
18176                            }
18177                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18178                            installRes.name = childPackageName;
18179                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18180                            installRes.pkg = mPackages.get(childPackageName);
18181                            installRes.uid = childPs.pkg.applicationInfo.uid;
18182                            if (outInfo.appearedChildPackages == null) {
18183                                outInfo.appearedChildPackages = new ArrayMap<>();
18184                            }
18185                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18186                        }
18187                    }
18188                }
18189            }
18190        }
18191
18192        return ret;
18193    }
18194
18195    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18196        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18197                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18198        for (int nextUserId : userIds) {
18199            if (DEBUG_REMOVE) {
18200                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18201            }
18202            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18203                    false /*installed*/,
18204                    true /*stopped*/,
18205                    true /*notLaunched*/,
18206                    false /*hidden*/,
18207                    false /*suspended*/,
18208                    false /*instantApp*/,
18209                    null /*lastDisableAppCaller*/,
18210                    null /*enabledComponents*/,
18211                    null /*disabledComponents*/,
18212                    false /*blockUninstall*/,
18213                    ps.readUserState(nextUserId).domainVerificationStatus,
18214                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18215        }
18216        mSettings.writeKernelMappingLPr(ps);
18217    }
18218
18219    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18220            PackageRemovedInfo outInfo) {
18221        final PackageParser.Package pkg;
18222        synchronized (mPackages) {
18223            pkg = mPackages.get(ps.name);
18224        }
18225
18226        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18227                : new int[] {userId};
18228        for (int nextUserId : userIds) {
18229            if (DEBUG_REMOVE) {
18230                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18231                        + nextUserId);
18232            }
18233
18234            destroyAppDataLIF(pkg, userId,
18235                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18236            destroyAppProfilesLIF(pkg, userId);
18237            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18238            schedulePackageCleaning(ps.name, nextUserId, false);
18239            synchronized (mPackages) {
18240                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18241                    scheduleWritePackageRestrictionsLocked(nextUserId);
18242                }
18243                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18244            }
18245        }
18246
18247        if (outInfo != null) {
18248            outInfo.removedPackage = ps.name;
18249            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18250            outInfo.removedAppId = ps.appId;
18251            outInfo.removedUsers = userIds;
18252        }
18253
18254        return true;
18255    }
18256
18257    private final class ClearStorageConnection implements ServiceConnection {
18258        IMediaContainerService mContainerService;
18259
18260        @Override
18261        public void onServiceConnected(ComponentName name, IBinder service) {
18262            synchronized (this) {
18263                mContainerService = IMediaContainerService.Stub
18264                        .asInterface(Binder.allowBlocking(service));
18265                notifyAll();
18266            }
18267        }
18268
18269        @Override
18270        public void onServiceDisconnected(ComponentName name) {
18271        }
18272    }
18273
18274    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18275        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18276
18277        final boolean mounted;
18278        if (Environment.isExternalStorageEmulated()) {
18279            mounted = true;
18280        } else {
18281            final String status = Environment.getExternalStorageState();
18282
18283            mounted = status.equals(Environment.MEDIA_MOUNTED)
18284                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18285        }
18286
18287        if (!mounted) {
18288            return;
18289        }
18290
18291        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18292        int[] users;
18293        if (userId == UserHandle.USER_ALL) {
18294            users = sUserManager.getUserIds();
18295        } else {
18296            users = new int[] { userId };
18297        }
18298        final ClearStorageConnection conn = new ClearStorageConnection();
18299        if (mContext.bindServiceAsUser(
18300                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18301            try {
18302                for (int curUser : users) {
18303                    long timeout = SystemClock.uptimeMillis() + 5000;
18304                    synchronized (conn) {
18305                        long now;
18306                        while (conn.mContainerService == null &&
18307                                (now = SystemClock.uptimeMillis()) < timeout) {
18308                            try {
18309                                conn.wait(timeout - now);
18310                            } catch (InterruptedException e) {
18311                            }
18312                        }
18313                    }
18314                    if (conn.mContainerService == null) {
18315                        return;
18316                    }
18317
18318                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18319                    clearDirectory(conn.mContainerService,
18320                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18321                    if (allData) {
18322                        clearDirectory(conn.mContainerService,
18323                                userEnv.buildExternalStorageAppDataDirs(packageName));
18324                        clearDirectory(conn.mContainerService,
18325                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18326                    }
18327                }
18328            } finally {
18329                mContext.unbindService(conn);
18330            }
18331        }
18332    }
18333
18334    @Override
18335    public void clearApplicationProfileData(String packageName) {
18336        enforceSystemOrRoot("Only the system can clear all profile data");
18337
18338        final PackageParser.Package pkg;
18339        synchronized (mPackages) {
18340            pkg = mPackages.get(packageName);
18341        }
18342
18343        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18344            synchronized (mInstallLock) {
18345                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18346            }
18347        }
18348    }
18349
18350    @Override
18351    public void clearApplicationUserData(final String packageName,
18352            final IPackageDataObserver observer, final int userId) {
18353        mContext.enforceCallingOrSelfPermission(
18354                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18355
18356        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18357                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18358
18359        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18360            throw new SecurityException("Cannot clear data for a protected package: "
18361                    + packageName);
18362        }
18363        // Queue up an async operation since the package deletion may take a little while.
18364        mHandler.post(new Runnable() {
18365            public void run() {
18366                mHandler.removeCallbacks(this);
18367                final boolean succeeded;
18368                try (PackageFreezer freezer = freezePackage(packageName,
18369                        "clearApplicationUserData")) {
18370                    synchronized (mInstallLock) {
18371                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18372                    }
18373                    clearExternalStorageDataSync(packageName, userId, true);
18374                    synchronized (mPackages) {
18375                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18376                                packageName, userId);
18377                    }
18378                }
18379                if (succeeded) {
18380                    // invoke DeviceStorageMonitor's update method to clear any notifications
18381                    DeviceStorageMonitorInternal dsm = LocalServices
18382                            .getService(DeviceStorageMonitorInternal.class);
18383                    if (dsm != null) {
18384                        dsm.checkMemory();
18385                    }
18386                }
18387                if(observer != null) {
18388                    try {
18389                        observer.onRemoveCompleted(packageName, succeeded);
18390                    } catch (RemoteException e) {
18391                        Log.i(TAG, "Observer no longer exists.");
18392                    }
18393                } //end if observer
18394            } //end run
18395        });
18396    }
18397
18398    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18399        if (packageName == null) {
18400            Slog.w(TAG, "Attempt to delete null packageName.");
18401            return false;
18402        }
18403
18404        // Try finding details about the requested package
18405        PackageParser.Package pkg;
18406        synchronized (mPackages) {
18407            pkg = mPackages.get(packageName);
18408            if (pkg == null) {
18409                final PackageSetting ps = mSettings.mPackages.get(packageName);
18410                if (ps != null) {
18411                    pkg = ps.pkg;
18412                }
18413            }
18414
18415            if (pkg == null) {
18416                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18417                return false;
18418            }
18419
18420            PackageSetting ps = (PackageSetting) pkg.mExtras;
18421            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18422        }
18423
18424        clearAppDataLIF(pkg, userId,
18425                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18426
18427        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18428        removeKeystoreDataIfNeeded(userId, appId);
18429
18430        UserManagerInternal umInternal = getUserManagerInternal();
18431        final int flags;
18432        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18433            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18434        } else if (umInternal.isUserRunning(userId)) {
18435            flags = StorageManager.FLAG_STORAGE_DE;
18436        } else {
18437            flags = 0;
18438        }
18439        prepareAppDataContentsLIF(pkg, userId, flags);
18440
18441        return true;
18442    }
18443
18444    /**
18445     * Reverts user permission state changes (permissions and flags) in
18446     * all packages for a given user.
18447     *
18448     * @param userId The device user for which to do a reset.
18449     */
18450    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18451        final int packageCount = mPackages.size();
18452        for (int i = 0; i < packageCount; i++) {
18453            PackageParser.Package pkg = mPackages.valueAt(i);
18454            PackageSetting ps = (PackageSetting) pkg.mExtras;
18455            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18456        }
18457    }
18458
18459    private void resetNetworkPolicies(int userId) {
18460        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18461    }
18462
18463    /**
18464     * Reverts user permission state changes (permissions and flags).
18465     *
18466     * @param ps The package for which to reset.
18467     * @param userId The device user for which to do a reset.
18468     */
18469    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18470            final PackageSetting ps, final int userId) {
18471        if (ps.pkg == null) {
18472            return;
18473        }
18474
18475        // These are flags that can change base on user actions.
18476        final int userSettableMask = FLAG_PERMISSION_USER_SET
18477                | FLAG_PERMISSION_USER_FIXED
18478                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18479                | FLAG_PERMISSION_REVIEW_REQUIRED;
18480
18481        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18482                | FLAG_PERMISSION_POLICY_FIXED;
18483
18484        boolean writeInstallPermissions = false;
18485        boolean writeRuntimePermissions = false;
18486
18487        final int permissionCount = ps.pkg.requestedPermissions.size();
18488        for (int i = 0; i < permissionCount; i++) {
18489            String permission = ps.pkg.requestedPermissions.get(i);
18490
18491            BasePermission bp = mSettings.mPermissions.get(permission);
18492            if (bp == null) {
18493                continue;
18494            }
18495
18496            // If shared user we just reset the state to which only this app contributed.
18497            if (ps.sharedUser != null) {
18498                boolean used = false;
18499                final int packageCount = ps.sharedUser.packages.size();
18500                for (int j = 0; j < packageCount; j++) {
18501                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18502                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18503                            && pkg.pkg.requestedPermissions.contains(permission)) {
18504                        used = true;
18505                        break;
18506                    }
18507                }
18508                if (used) {
18509                    continue;
18510                }
18511            }
18512
18513            PermissionsState permissionsState = ps.getPermissionsState();
18514
18515            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18516
18517            // Always clear the user settable flags.
18518            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18519                    bp.name) != null;
18520            // If permission review is enabled and this is a legacy app, mark the
18521            // permission as requiring a review as this is the initial state.
18522            int flags = 0;
18523            if (mPermissionReviewRequired
18524                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18525                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18526            }
18527            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18528                if (hasInstallState) {
18529                    writeInstallPermissions = true;
18530                } else {
18531                    writeRuntimePermissions = true;
18532                }
18533            }
18534
18535            // Below is only runtime permission handling.
18536            if (!bp.isRuntime()) {
18537                continue;
18538            }
18539
18540            // Never clobber system or policy.
18541            if ((oldFlags & policyOrSystemFlags) != 0) {
18542                continue;
18543            }
18544
18545            // If this permission was granted by default, make sure it is.
18546            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18547                if (permissionsState.grantRuntimePermission(bp, userId)
18548                        != PERMISSION_OPERATION_FAILURE) {
18549                    writeRuntimePermissions = true;
18550                }
18551            // If permission review is enabled the permissions for a legacy apps
18552            // are represented as constantly granted runtime ones, so don't revoke.
18553            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18554                // Otherwise, reset the permission.
18555                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18556                switch (revokeResult) {
18557                    case PERMISSION_OPERATION_SUCCESS:
18558                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18559                        writeRuntimePermissions = true;
18560                        final int appId = ps.appId;
18561                        mHandler.post(new Runnable() {
18562                            @Override
18563                            public void run() {
18564                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18565                            }
18566                        });
18567                    } break;
18568                }
18569            }
18570        }
18571
18572        // Synchronously write as we are taking permissions away.
18573        if (writeRuntimePermissions) {
18574            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18575        }
18576
18577        // Synchronously write as we are taking permissions away.
18578        if (writeInstallPermissions) {
18579            mSettings.writeLPr();
18580        }
18581    }
18582
18583    /**
18584     * Remove entries from the keystore daemon. Will only remove it if the
18585     * {@code appId} is valid.
18586     */
18587    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18588        if (appId < 0) {
18589            return;
18590        }
18591
18592        final KeyStore keyStore = KeyStore.getInstance();
18593        if (keyStore != null) {
18594            if (userId == UserHandle.USER_ALL) {
18595                for (final int individual : sUserManager.getUserIds()) {
18596                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18597                }
18598            } else {
18599                keyStore.clearUid(UserHandle.getUid(userId, appId));
18600            }
18601        } else {
18602            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18603        }
18604    }
18605
18606    @Override
18607    public void deleteApplicationCacheFiles(final String packageName,
18608            final IPackageDataObserver observer) {
18609        final int userId = UserHandle.getCallingUserId();
18610        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18611    }
18612
18613    @Override
18614    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18615            final IPackageDataObserver observer) {
18616        mContext.enforceCallingOrSelfPermission(
18617                android.Manifest.permission.DELETE_CACHE_FILES, null);
18618        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18619                /* requireFullPermission= */ true, /* checkShell= */ false,
18620                "delete application cache files");
18621
18622        final PackageParser.Package pkg;
18623        synchronized (mPackages) {
18624            pkg = mPackages.get(packageName);
18625        }
18626
18627        // Queue up an async operation since the package deletion may take a little while.
18628        mHandler.post(new Runnable() {
18629            public void run() {
18630                synchronized (mInstallLock) {
18631                    final int flags = StorageManager.FLAG_STORAGE_DE
18632                            | StorageManager.FLAG_STORAGE_CE;
18633                    // We're only clearing cache files, so we don't care if the
18634                    // app is unfrozen and still able to run
18635                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18636                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18637                }
18638                clearExternalStorageDataSync(packageName, userId, false);
18639                if (observer != null) {
18640                    try {
18641                        observer.onRemoveCompleted(packageName, true);
18642                    } catch (RemoteException e) {
18643                        Log.i(TAG, "Observer no longer exists.");
18644                    }
18645                }
18646            }
18647        });
18648    }
18649
18650    @Override
18651    public void getPackageSizeInfo(final String packageName, int userHandle,
18652            final IPackageStatsObserver observer) {
18653        throw new UnsupportedOperationException(
18654                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18655    }
18656
18657    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18658        final PackageSetting ps;
18659        synchronized (mPackages) {
18660            ps = mSettings.mPackages.get(packageName);
18661            if (ps == null) {
18662                Slog.w(TAG, "Failed to find settings for " + packageName);
18663                return false;
18664            }
18665        }
18666
18667        final String[] packageNames = { packageName };
18668        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18669        final String[] codePaths = { ps.codePathString };
18670
18671        try {
18672            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18673                    ps.appId, ceDataInodes, codePaths, stats);
18674
18675            // For now, ignore code size of packages on system partition
18676            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18677                stats.codeSize = 0;
18678            }
18679
18680            // External clients expect these to be tracked separately
18681            stats.dataSize -= stats.cacheSize;
18682
18683        } catch (InstallerException e) {
18684            Slog.w(TAG, String.valueOf(e));
18685            return false;
18686        }
18687
18688        return true;
18689    }
18690
18691    private int getUidTargetSdkVersionLockedLPr(int uid) {
18692        Object obj = mSettings.getUserIdLPr(uid);
18693        if (obj instanceof SharedUserSetting) {
18694            final SharedUserSetting sus = (SharedUserSetting) obj;
18695            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18696            final Iterator<PackageSetting> it = sus.packages.iterator();
18697            while (it.hasNext()) {
18698                final PackageSetting ps = it.next();
18699                if (ps.pkg != null) {
18700                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18701                    if (v < vers) vers = v;
18702                }
18703            }
18704            return vers;
18705        } else if (obj instanceof PackageSetting) {
18706            final PackageSetting ps = (PackageSetting) obj;
18707            if (ps.pkg != null) {
18708                return ps.pkg.applicationInfo.targetSdkVersion;
18709            }
18710        }
18711        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18712    }
18713
18714    @Override
18715    public void addPreferredActivity(IntentFilter filter, int match,
18716            ComponentName[] set, ComponentName activity, int userId) {
18717        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18718                "Adding preferred");
18719    }
18720
18721    private void addPreferredActivityInternal(IntentFilter filter, int match,
18722            ComponentName[] set, ComponentName activity, boolean always, int userId,
18723            String opname) {
18724        // writer
18725        int callingUid = Binder.getCallingUid();
18726        enforceCrossUserPermission(callingUid, userId,
18727                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18728        if (filter.countActions() == 0) {
18729            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18730            return;
18731        }
18732        synchronized (mPackages) {
18733            if (mContext.checkCallingOrSelfPermission(
18734                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18735                    != PackageManager.PERMISSION_GRANTED) {
18736                if (getUidTargetSdkVersionLockedLPr(callingUid)
18737                        < Build.VERSION_CODES.FROYO) {
18738                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18739                            + callingUid);
18740                    return;
18741                }
18742                mContext.enforceCallingOrSelfPermission(
18743                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18744            }
18745
18746            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18747            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18748                    + userId + ":");
18749            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18750            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18751            scheduleWritePackageRestrictionsLocked(userId);
18752            postPreferredActivityChangedBroadcast(userId);
18753        }
18754    }
18755
18756    private void postPreferredActivityChangedBroadcast(int userId) {
18757        mHandler.post(() -> {
18758            final IActivityManager am = ActivityManager.getService();
18759            if (am == null) {
18760                return;
18761            }
18762
18763            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18764            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18765            try {
18766                am.broadcastIntent(null, intent, null, null,
18767                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18768                        null, false, false, userId);
18769            } catch (RemoteException e) {
18770            }
18771        });
18772    }
18773
18774    @Override
18775    public void replacePreferredActivity(IntentFilter filter, int match,
18776            ComponentName[] set, ComponentName activity, int userId) {
18777        if (filter.countActions() != 1) {
18778            throw new IllegalArgumentException(
18779                    "replacePreferredActivity expects filter to have only 1 action.");
18780        }
18781        if (filter.countDataAuthorities() != 0
18782                || filter.countDataPaths() != 0
18783                || filter.countDataSchemes() > 1
18784                || filter.countDataTypes() != 0) {
18785            throw new IllegalArgumentException(
18786                    "replacePreferredActivity expects filter to have no data authorities, " +
18787                    "paths, or types; and at most one scheme.");
18788        }
18789
18790        final int callingUid = Binder.getCallingUid();
18791        enforceCrossUserPermission(callingUid, userId,
18792                true /* requireFullPermission */, false /* checkShell */,
18793                "replace preferred activity");
18794        synchronized (mPackages) {
18795            if (mContext.checkCallingOrSelfPermission(
18796                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18797                    != PackageManager.PERMISSION_GRANTED) {
18798                if (getUidTargetSdkVersionLockedLPr(callingUid)
18799                        < Build.VERSION_CODES.FROYO) {
18800                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18801                            + Binder.getCallingUid());
18802                    return;
18803                }
18804                mContext.enforceCallingOrSelfPermission(
18805                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18806            }
18807
18808            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18809            if (pir != null) {
18810                // Get all of the existing entries that exactly match this filter.
18811                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18812                if (existing != null && existing.size() == 1) {
18813                    PreferredActivity cur = existing.get(0);
18814                    if (DEBUG_PREFERRED) {
18815                        Slog.i(TAG, "Checking replace of preferred:");
18816                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18817                        if (!cur.mPref.mAlways) {
18818                            Slog.i(TAG, "  -- CUR; not mAlways!");
18819                        } else {
18820                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18821                            Slog.i(TAG, "  -- CUR: mSet="
18822                                    + Arrays.toString(cur.mPref.mSetComponents));
18823                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18824                            Slog.i(TAG, "  -- NEW: mMatch="
18825                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18826                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18827                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18828                        }
18829                    }
18830                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18831                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18832                            && cur.mPref.sameSet(set)) {
18833                        // Setting the preferred activity to what it happens to be already
18834                        if (DEBUG_PREFERRED) {
18835                            Slog.i(TAG, "Replacing with same preferred activity "
18836                                    + cur.mPref.mShortComponent + " for user "
18837                                    + userId + ":");
18838                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18839                        }
18840                        return;
18841                    }
18842                }
18843
18844                if (existing != null) {
18845                    if (DEBUG_PREFERRED) {
18846                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18847                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18848                    }
18849                    for (int i = 0; i < existing.size(); i++) {
18850                        PreferredActivity pa = existing.get(i);
18851                        if (DEBUG_PREFERRED) {
18852                            Slog.i(TAG, "Removing existing preferred activity "
18853                                    + pa.mPref.mComponent + ":");
18854                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18855                        }
18856                        pir.removeFilter(pa);
18857                    }
18858                }
18859            }
18860            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18861                    "Replacing preferred");
18862        }
18863    }
18864
18865    @Override
18866    public void clearPackagePreferredActivities(String packageName) {
18867        final int uid = Binder.getCallingUid();
18868        // writer
18869        synchronized (mPackages) {
18870            PackageParser.Package pkg = mPackages.get(packageName);
18871            if (pkg == null || pkg.applicationInfo.uid != uid) {
18872                if (mContext.checkCallingOrSelfPermission(
18873                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18874                        != PackageManager.PERMISSION_GRANTED) {
18875                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18876                            < Build.VERSION_CODES.FROYO) {
18877                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18878                                + Binder.getCallingUid());
18879                        return;
18880                    }
18881                    mContext.enforceCallingOrSelfPermission(
18882                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18883                }
18884            }
18885
18886            int user = UserHandle.getCallingUserId();
18887            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18888                scheduleWritePackageRestrictionsLocked(user);
18889            }
18890        }
18891    }
18892
18893    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18894    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18895        ArrayList<PreferredActivity> removed = null;
18896        boolean changed = false;
18897        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18898            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18899            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18900            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18901                continue;
18902            }
18903            Iterator<PreferredActivity> it = pir.filterIterator();
18904            while (it.hasNext()) {
18905                PreferredActivity pa = it.next();
18906                // Mark entry for removal only if it matches the package name
18907                // and the entry is of type "always".
18908                if (packageName == null ||
18909                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18910                                && pa.mPref.mAlways)) {
18911                    if (removed == null) {
18912                        removed = new ArrayList<PreferredActivity>();
18913                    }
18914                    removed.add(pa);
18915                }
18916            }
18917            if (removed != null) {
18918                for (int j=0; j<removed.size(); j++) {
18919                    PreferredActivity pa = removed.get(j);
18920                    pir.removeFilter(pa);
18921                }
18922                changed = true;
18923            }
18924        }
18925        if (changed) {
18926            postPreferredActivityChangedBroadcast(userId);
18927        }
18928        return changed;
18929    }
18930
18931    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18932    private void clearIntentFilterVerificationsLPw(int userId) {
18933        final int packageCount = mPackages.size();
18934        for (int i = 0; i < packageCount; i++) {
18935            PackageParser.Package pkg = mPackages.valueAt(i);
18936            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18937        }
18938    }
18939
18940    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18941    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18942        if (userId == UserHandle.USER_ALL) {
18943            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18944                    sUserManager.getUserIds())) {
18945                for (int oneUserId : sUserManager.getUserIds()) {
18946                    scheduleWritePackageRestrictionsLocked(oneUserId);
18947                }
18948            }
18949        } else {
18950            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18951                scheduleWritePackageRestrictionsLocked(userId);
18952            }
18953        }
18954    }
18955
18956    void clearDefaultBrowserIfNeeded(String packageName) {
18957        for (int oneUserId : sUserManager.getUserIds()) {
18958            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18959            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18960            if (packageName.equals(defaultBrowserPackageName)) {
18961                setDefaultBrowserPackageName(null, oneUserId);
18962            }
18963        }
18964    }
18965
18966    @Override
18967    public void resetApplicationPreferences(int userId) {
18968        mContext.enforceCallingOrSelfPermission(
18969                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18970        final long identity = Binder.clearCallingIdentity();
18971        // writer
18972        try {
18973            synchronized (mPackages) {
18974                clearPackagePreferredActivitiesLPw(null, userId);
18975                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18976                // TODO: We have to reset the default SMS and Phone. This requires
18977                // significant refactoring to keep all default apps in the package
18978                // manager (cleaner but more work) or have the services provide
18979                // callbacks to the package manager to request a default app reset.
18980                applyFactoryDefaultBrowserLPw(userId);
18981                clearIntentFilterVerificationsLPw(userId);
18982                primeDomainVerificationsLPw(userId);
18983                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18984                scheduleWritePackageRestrictionsLocked(userId);
18985            }
18986            resetNetworkPolicies(userId);
18987        } finally {
18988            Binder.restoreCallingIdentity(identity);
18989        }
18990    }
18991
18992    @Override
18993    public int getPreferredActivities(List<IntentFilter> outFilters,
18994            List<ComponentName> outActivities, String packageName) {
18995
18996        int num = 0;
18997        final int userId = UserHandle.getCallingUserId();
18998        // reader
18999        synchronized (mPackages) {
19000            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19001            if (pir != null) {
19002                final Iterator<PreferredActivity> it = pir.filterIterator();
19003                while (it.hasNext()) {
19004                    final PreferredActivity pa = it.next();
19005                    if (packageName == null
19006                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19007                                    && pa.mPref.mAlways)) {
19008                        if (outFilters != null) {
19009                            outFilters.add(new IntentFilter(pa));
19010                        }
19011                        if (outActivities != null) {
19012                            outActivities.add(pa.mPref.mComponent);
19013                        }
19014                    }
19015                }
19016            }
19017        }
19018
19019        return num;
19020    }
19021
19022    @Override
19023    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19024            int userId) {
19025        int callingUid = Binder.getCallingUid();
19026        if (callingUid != Process.SYSTEM_UID) {
19027            throw new SecurityException(
19028                    "addPersistentPreferredActivity can only be run by the system");
19029        }
19030        if (filter.countActions() == 0) {
19031            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19032            return;
19033        }
19034        synchronized (mPackages) {
19035            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19036                    ":");
19037            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19038            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19039                    new PersistentPreferredActivity(filter, activity));
19040            scheduleWritePackageRestrictionsLocked(userId);
19041            postPreferredActivityChangedBroadcast(userId);
19042        }
19043    }
19044
19045    @Override
19046    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19047        int callingUid = Binder.getCallingUid();
19048        if (callingUid != Process.SYSTEM_UID) {
19049            throw new SecurityException(
19050                    "clearPackagePersistentPreferredActivities can only be run by the system");
19051        }
19052        ArrayList<PersistentPreferredActivity> removed = null;
19053        boolean changed = false;
19054        synchronized (mPackages) {
19055            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19056                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19057                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19058                        .valueAt(i);
19059                if (userId != thisUserId) {
19060                    continue;
19061                }
19062                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19063                while (it.hasNext()) {
19064                    PersistentPreferredActivity ppa = it.next();
19065                    // Mark entry for removal only if it matches the package name.
19066                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19067                        if (removed == null) {
19068                            removed = new ArrayList<PersistentPreferredActivity>();
19069                        }
19070                        removed.add(ppa);
19071                    }
19072                }
19073                if (removed != null) {
19074                    for (int j=0; j<removed.size(); j++) {
19075                        PersistentPreferredActivity ppa = removed.get(j);
19076                        ppir.removeFilter(ppa);
19077                    }
19078                    changed = true;
19079                }
19080            }
19081
19082            if (changed) {
19083                scheduleWritePackageRestrictionsLocked(userId);
19084                postPreferredActivityChangedBroadcast(userId);
19085            }
19086        }
19087    }
19088
19089    /**
19090     * Common machinery for picking apart a restored XML blob and passing
19091     * it to a caller-supplied functor to be applied to the running system.
19092     */
19093    private void restoreFromXml(XmlPullParser parser, int userId,
19094            String expectedStartTag, BlobXmlRestorer functor)
19095            throws IOException, XmlPullParserException {
19096        int type;
19097        while ((type = parser.next()) != XmlPullParser.START_TAG
19098                && type != XmlPullParser.END_DOCUMENT) {
19099        }
19100        if (type != XmlPullParser.START_TAG) {
19101            // oops didn't find a start tag?!
19102            if (DEBUG_BACKUP) {
19103                Slog.e(TAG, "Didn't find start tag during restore");
19104            }
19105            return;
19106        }
19107Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19108        // this is supposed to be TAG_PREFERRED_BACKUP
19109        if (!expectedStartTag.equals(parser.getName())) {
19110            if (DEBUG_BACKUP) {
19111                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19112            }
19113            return;
19114        }
19115
19116        // skip interfering stuff, then we're aligned with the backing implementation
19117        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19118Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19119        functor.apply(parser, userId);
19120    }
19121
19122    private interface BlobXmlRestorer {
19123        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19124    }
19125
19126    /**
19127     * Non-Binder method, support for the backup/restore mechanism: write the
19128     * full set of preferred activities in its canonical XML format.  Returns the
19129     * XML output as a byte array, or null if there is none.
19130     */
19131    @Override
19132    public byte[] getPreferredActivityBackup(int userId) {
19133        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19134            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19135        }
19136
19137        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19138        try {
19139            final XmlSerializer serializer = new FastXmlSerializer();
19140            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19141            serializer.startDocument(null, true);
19142            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19143
19144            synchronized (mPackages) {
19145                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19146            }
19147
19148            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19149            serializer.endDocument();
19150            serializer.flush();
19151        } catch (Exception e) {
19152            if (DEBUG_BACKUP) {
19153                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19154            }
19155            return null;
19156        }
19157
19158        return dataStream.toByteArray();
19159    }
19160
19161    @Override
19162    public void restorePreferredActivities(byte[] backup, int userId) {
19163        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19164            throw new SecurityException("Only the system may call restorePreferredActivities()");
19165        }
19166
19167        try {
19168            final XmlPullParser parser = Xml.newPullParser();
19169            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19170            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19171                    new BlobXmlRestorer() {
19172                        @Override
19173                        public void apply(XmlPullParser parser, int userId)
19174                                throws XmlPullParserException, IOException {
19175                            synchronized (mPackages) {
19176                                mSettings.readPreferredActivitiesLPw(parser, userId);
19177                            }
19178                        }
19179                    } );
19180        } catch (Exception e) {
19181            if (DEBUG_BACKUP) {
19182                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19183            }
19184        }
19185    }
19186
19187    /**
19188     * Non-Binder method, support for the backup/restore mechanism: write the
19189     * default browser (etc) settings in its canonical XML format.  Returns the default
19190     * browser XML representation as a byte array, or null if there is none.
19191     */
19192    @Override
19193    public byte[] getDefaultAppsBackup(int userId) {
19194        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19195            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19196        }
19197
19198        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19199        try {
19200            final XmlSerializer serializer = new FastXmlSerializer();
19201            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19202            serializer.startDocument(null, true);
19203            serializer.startTag(null, TAG_DEFAULT_APPS);
19204
19205            synchronized (mPackages) {
19206                mSettings.writeDefaultAppsLPr(serializer, userId);
19207            }
19208
19209            serializer.endTag(null, TAG_DEFAULT_APPS);
19210            serializer.endDocument();
19211            serializer.flush();
19212        } catch (Exception e) {
19213            if (DEBUG_BACKUP) {
19214                Slog.e(TAG, "Unable to write default apps for backup", e);
19215            }
19216            return null;
19217        }
19218
19219        return dataStream.toByteArray();
19220    }
19221
19222    @Override
19223    public void restoreDefaultApps(byte[] backup, int userId) {
19224        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19225            throw new SecurityException("Only the system may call restoreDefaultApps()");
19226        }
19227
19228        try {
19229            final XmlPullParser parser = Xml.newPullParser();
19230            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19231            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19232                    new BlobXmlRestorer() {
19233                        @Override
19234                        public void apply(XmlPullParser parser, int userId)
19235                                throws XmlPullParserException, IOException {
19236                            synchronized (mPackages) {
19237                                mSettings.readDefaultAppsLPw(parser, userId);
19238                            }
19239                        }
19240                    } );
19241        } catch (Exception e) {
19242            if (DEBUG_BACKUP) {
19243                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19244            }
19245        }
19246    }
19247
19248    @Override
19249    public byte[] getIntentFilterVerificationBackup(int userId) {
19250        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19251            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19252        }
19253
19254        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19255        try {
19256            final XmlSerializer serializer = new FastXmlSerializer();
19257            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19258            serializer.startDocument(null, true);
19259            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19260
19261            synchronized (mPackages) {
19262                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19263            }
19264
19265            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19266            serializer.endDocument();
19267            serializer.flush();
19268        } catch (Exception e) {
19269            if (DEBUG_BACKUP) {
19270                Slog.e(TAG, "Unable to write default apps for backup", e);
19271            }
19272            return null;
19273        }
19274
19275        return dataStream.toByteArray();
19276    }
19277
19278    @Override
19279    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19280        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19281            throw new SecurityException("Only the system may call restorePreferredActivities()");
19282        }
19283
19284        try {
19285            final XmlPullParser parser = Xml.newPullParser();
19286            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19287            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19288                    new BlobXmlRestorer() {
19289                        @Override
19290                        public void apply(XmlPullParser parser, int userId)
19291                                throws XmlPullParserException, IOException {
19292                            synchronized (mPackages) {
19293                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19294                                mSettings.writeLPr();
19295                            }
19296                        }
19297                    } );
19298        } catch (Exception e) {
19299            if (DEBUG_BACKUP) {
19300                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19301            }
19302        }
19303    }
19304
19305    @Override
19306    public byte[] getPermissionGrantBackup(int userId) {
19307        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19308            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19309        }
19310
19311        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19312        try {
19313            final XmlSerializer serializer = new FastXmlSerializer();
19314            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19315            serializer.startDocument(null, true);
19316            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19317
19318            synchronized (mPackages) {
19319                serializeRuntimePermissionGrantsLPr(serializer, userId);
19320            }
19321
19322            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19323            serializer.endDocument();
19324            serializer.flush();
19325        } catch (Exception e) {
19326            if (DEBUG_BACKUP) {
19327                Slog.e(TAG, "Unable to write default apps for backup", e);
19328            }
19329            return null;
19330        }
19331
19332        return dataStream.toByteArray();
19333    }
19334
19335    @Override
19336    public void restorePermissionGrants(byte[] backup, int userId) {
19337        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19338            throw new SecurityException("Only the system may call restorePermissionGrants()");
19339        }
19340
19341        try {
19342            final XmlPullParser parser = Xml.newPullParser();
19343            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19344            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19345                    new BlobXmlRestorer() {
19346                        @Override
19347                        public void apply(XmlPullParser parser, int userId)
19348                                throws XmlPullParserException, IOException {
19349                            synchronized (mPackages) {
19350                                processRestoredPermissionGrantsLPr(parser, userId);
19351                            }
19352                        }
19353                    } );
19354        } catch (Exception e) {
19355            if (DEBUG_BACKUP) {
19356                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19357            }
19358        }
19359    }
19360
19361    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19362            throws IOException {
19363        serializer.startTag(null, TAG_ALL_GRANTS);
19364
19365        final int N = mSettings.mPackages.size();
19366        for (int i = 0; i < N; i++) {
19367            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19368            boolean pkgGrantsKnown = false;
19369
19370            PermissionsState packagePerms = ps.getPermissionsState();
19371
19372            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19373                final int grantFlags = state.getFlags();
19374                // only look at grants that are not system/policy fixed
19375                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19376                    final boolean isGranted = state.isGranted();
19377                    // And only back up the user-twiddled state bits
19378                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19379                        final String packageName = mSettings.mPackages.keyAt(i);
19380                        if (!pkgGrantsKnown) {
19381                            serializer.startTag(null, TAG_GRANT);
19382                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19383                            pkgGrantsKnown = true;
19384                        }
19385
19386                        final boolean userSet =
19387                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19388                        final boolean userFixed =
19389                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19390                        final boolean revoke =
19391                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19392
19393                        serializer.startTag(null, TAG_PERMISSION);
19394                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19395                        if (isGranted) {
19396                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19397                        }
19398                        if (userSet) {
19399                            serializer.attribute(null, ATTR_USER_SET, "true");
19400                        }
19401                        if (userFixed) {
19402                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19403                        }
19404                        if (revoke) {
19405                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19406                        }
19407                        serializer.endTag(null, TAG_PERMISSION);
19408                    }
19409                }
19410            }
19411
19412            if (pkgGrantsKnown) {
19413                serializer.endTag(null, TAG_GRANT);
19414            }
19415        }
19416
19417        serializer.endTag(null, TAG_ALL_GRANTS);
19418    }
19419
19420    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19421            throws XmlPullParserException, IOException {
19422        String pkgName = null;
19423        int outerDepth = parser.getDepth();
19424        int type;
19425        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19426                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19427            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19428                continue;
19429            }
19430
19431            final String tagName = parser.getName();
19432            if (tagName.equals(TAG_GRANT)) {
19433                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19434                if (DEBUG_BACKUP) {
19435                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19436                }
19437            } else if (tagName.equals(TAG_PERMISSION)) {
19438
19439                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19440                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19441
19442                int newFlagSet = 0;
19443                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19444                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19445                }
19446                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19447                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19448                }
19449                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19450                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19451                }
19452                if (DEBUG_BACKUP) {
19453                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19454                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19455                }
19456                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19457                if (ps != null) {
19458                    // Already installed so we apply the grant immediately
19459                    if (DEBUG_BACKUP) {
19460                        Slog.v(TAG, "        + already installed; applying");
19461                    }
19462                    PermissionsState perms = ps.getPermissionsState();
19463                    BasePermission bp = mSettings.mPermissions.get(permName);
19464                    if (bp != null) {
19465                        if (isGranted) {
19466                            perms.grantRuntimePermission(bp, userId);
19467                        }
19468                        if (newFlagSet != 0) {
19469                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19470                        }
19471                    }
19472                } else {
19473                    // Need to wait for post-restore install to apply the grant
19474                    if (DEBUG_BACKUP) {
19475                        Slog.v(TAG, "        - not yet installed; saving for later");
19476                    }
19477                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19478                            isGranted, newFlagSet, userId);
19479                }
19480            } else {
19481                PackageManagerService.reportSettingsProblem(Log.WARN,
19482                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19483                XmlUtils.skipCurrentTag(parser);
19484            }
19485        }
19486
19487        scheduleWriteSettingsLocked();
19488        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19489    }
19490
19491    @Override
19492    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19493            int sourceUserId, int targetUserId, int flags) {
19494        mContext.enforceCallingOrSelfPermission(
19495                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19496        int callingUid = Binder.getCallingUid();
19497        enforceOwnerRights(ownerPackage, callingUid);
19498        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19499        if (intentFilter.countActions() == 0) {
19500            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19501            return;
19502        }
19503        synchronized (mPackages) {
19504            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19505                    ownerPackage, targetUserId, flags);
19506            CrossProfileIntentResolver resolver =
19507                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19508            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19509            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19510            if (existing != null) {
19511                int size = existing.size();
19512                for (int i = 0; i < size; i++) {
19513                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19514                        return;
19515                    }
19516                }
19517            }
19518            resolver.addFilter(newFilter);
19519            scheduleWritePackageRestrictionsLocked(sourceUserId);
19520        }
19521    }
19522
19523    @Override
19524    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19525        mContext.enforceCallingOrSelfPermission(
19526                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19527        int callingUid = Binder.getCallingUid();
19528        enforceOwnerRights(ownerPackage, callingUid);
19529        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19530        synchronized (mPackages) {
19531            CrossProfileIntentResolver resolver =
19532                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19533            ArraySet<CrossProfileIntentFilter> set =
19534                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19535            for (CrossProfileIntentFilter filter : set) {
19536                if (filter.getOwnerPackage().equals(ownerPackage)) {
19537                    resolver.removeFilter(filter);
19538                }
19539            }
19540            scheduleWritePackageRestrictionsLocked(sourceUserId);
19541        }
19542    }
19543
19544    // Enforcing that callingUid is owning pkg on userId
19545    private void enforceOwnerRights(String pkg, int callingUid) {
19546        // The system owns everything.
19547        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19548            return;
19549        }
19550        int callingUserId = UserHandle.getUserId(callingUid);
19551        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19552        if (pi == null) {
19553            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19554                    + callingUserId);
19555        }
19556        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19557            throw new SecurityException("Calling uid " + callingUid
19558                    + " does not own package " + pkg);
19559        }
19560    }
19561
19562    @Override
19563    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19564        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19565    }
19566
19567    /**
19568     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19569     * then reports the most likely home activity or null if there are more than one.
19570     */
19571    public ComponentName getDefaultHomeActivity(int userId) {
19572        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19573        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19574        if (cn != null) {
19575            return cn;
19576        }
19577
19578        // Find the launcher with the highest priority and return that component if there are no
19579        // other home activity with the same priority.
19580        int lastPriority = Integer.MIN_VALUE;
19581        ComponentName lastComponent = null;
19582        final int size = allHomeCandidates.size();
19583        for (int i = 0; i < size; i++) {
19584            final ResolveInfo ri = allHomeCandidates.get(i);
19585            if (ri.priority > lastPriority) {
19586                lastComponent = ri.activityInfo.getComponentName();
19587                lastPriority = ri.priority;
19588            } else if (ri.priority == lastPriority) {
19589                // Two components found with same priority.
19590                lastComponent = null;
19591            }
19592        }
19593        return lastComponent;
19594    }
19595
19596    private Intent getHomeIntent() {
19597        Intent intent = new Intent(Intent.ACTION_MAIN);
19598        intent.addCategory(Intent.CATEGORY_HOME);
19599        intent.addCategory(Intent.CATEGORY_DEFAULT);
19600        return intent;
19601    }
19602
19603    private IntentFilter getHomeFilter() {
19604        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19605        filter.addCategory(Intent.CATEGORY_HOME);
19606        filter.addCategory(Intent.CATEGORY_DEFAULT);
19607        return filter;
19608    }
19609
19610    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19611            int userId) {
19612        Intent intent  = getHomeIntent();
19613        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19614                PackageManager.GET_META_DATA, userId);
19615        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19616                true, false, false, userId);
19617
19618        allHomeCandidates.clear();
19619        if (list != null) {
19620            for (ResolveInfo ri : list) {
19621                allHomeCandidates.add(ri);
19622            }
19623        }
19624        return (preferred == null || preferred.activityInfo == null)
19625                ? null
19626                : new ComponentName(preferred.activityInfo.packageName,
19627                        preferred.activityInfo.name);
19628    }
19629
19630    @Override
19631    public void setHomeActivity(ComponentName comp, int userId) {
19632        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19633        getHomeActivitiesAsUser(homeActivities, userId);
19634
19635        boolean found = false;
19636
19637        final int size = homeActivities.size();
19638        final ComponentName[] set = new ComponentName[size];
19639        for (int i = 0; i < size; i++) {
19640            final ResolveInfo candidate = homeActivities.get(i);
19641            final ActivityInfo info = candidate.activityInfo;
19642            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19643            set[i] = activityName;
19644            if (!found && activityName.equals(comp)) {
19645                found = true;
19646            }
19647        }
19648        if (!found) {
19649            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19650                    + userId);
19651        }
19652        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19653                set, comp, userId);
19654    }
19655
19656    private @Nullable String getSetupWizardPackageName() {
19657        final Intent intent = new Intent(Intent.ACTION_MAIN);
19658        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19659
19660        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19661                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19662                        | MATCH_DISABLED_COMPONENTS,
19663                UserHandle.myUserId());
19664        if (matches.size() == 1) {
19665            return matches.get(0).getComponentInfo().packageName;
19666        } else {
19667            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19668                    + ": matches=" + matches);
19669            return null;
19670        }
19671    }
19672
19673    private @Nullable String getStorageManagerPackageName() {
19674        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19675
19676        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19677                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19678                        | MATCH_DISABLED_COMPONENTS,
19679                UserHandle.myUserId());
19680        if (matches.size() == 1) {
19681            return matches.get(0).getComponentInfo().packageName;
19682        } else {
19683            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19684                    + matches.size() + ": matches=" + matches);
19685            return null;
19686        }
19687    }
19688
19689    @Override
19690    public void setApplicationEnabledSetting(String appPackageName,
19691            int newState, int flags, int userId, String callingPackage) {
19692        if (!sUserManager.exists(userId)) return;
19693        if (callingPackage == null) {
19694            callingPackage = Integer.toString(Binder.getCallingUid());
19695        }
19696        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19697    }
19698
19699    @Override
19700    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19701        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19702        synchronized (mPackages) {
19703            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19704            if (pkgSetting != null) {
19705                pkgSetting.setUpdateAvailable(updateAvailable);
19706            }
19707        }
19708    }
19709
19710    @Override
19711    public void setComponentEnabledSetting(ComponentName componentName,
19712            int newState, int flags, int userId) {
19713        if (!sUserManager.exists(userId)) return;
19714        setEnabledSetting(componentName.getPackageName(),
19715                componentName.getClassName(), newState, flags, userId, null);
19716    }
19717
19718    private void setEnabledSetting(final String packageName, String className, int newState,
19719            final int flags, int userId, String callingPackage) {
19720        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19721              || newState == COMPONENT_ENABLED_STATE_ENABLED
19722              || newState == COMPONENT_ENABLED_STATE_DISABLED
19723              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19724              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19725            throw new IllegalArgumentException("Invalid new component state: "
19726                    + newState);
19727        }
19728        PackageSetting pkgSetting;
19729        final int uid = Binder.getCallingUid();
19730        final int permission;
19731        if (uid == Process.SYSTEM_UID) {
19732            permission = PackageManager.PERMISSION_GRANTED;
19733        } else {
19734            permission = mContext.checkCallingOrSelfPermission(
19735                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19736        }
19737        enforceCrossUserPermission(uid, userId,
19738                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19739        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19740        boolean sendNow = false;
19741        boolean isApp = (className == null);
19742        String componentName = isApp ? packageName : className;
19743        int packageUid = -1;
19744        ArrayList<String> components;
19745
19746        // writer
19747        synchronized (mPackages) {
19748            pkgSetting = mSettings.mPackages.get(packageName);
19749            if (pkgSetting == null) {
19750                if (className == null) {
19751                    throw new IllegalArgumentException("Unknown package: " + packageName);
19752                }
19753                throw new IllegalArgumentException(
19754                        "Unknown component: " + packageName + "/" + className);
19755            }
19756        }
19757
19758        // Limit who can change which apps
19759        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19760            // Don't allow apps that don't have permission to modify other apps
19761            if (!allowedByPermission) {
19762                throw new SecurityException(
19763                        "Permission Denial: attempt to change component state from pid="
19764                        + Binder.getCallingPid()
19765                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19766            }
19767            // Don't allow changing protected packages.
19768            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19769                throw new SecurityException("Cannot disable a protected package: " + packageName);
19770            }
19771        }
19772
19773        synchronized (mPackages) {
19774            if (uid == Process.SHELL_UID
19775                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19776                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19777                // unless it is a test package.
19778                int oldState = pkgSetting.getEnabled(userId);
19779                if (className == null
19780                    &&
19781                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19782                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19783                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19784                    &&
19785                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19786                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19787                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19788                    // ok
19789                } else {
19790                    throw new SecurityException(
19791                            "Shell cannot change component state for " + packageName + "/"
19792                            + className + " to " + newState);
19793                }
19794            }
19795            if (className == null) {
19796                // We're dealing with an application/package level state change
19797                if (pkgSetting.getEnabled(userId) == newState) {
19798                    // Nothing to do
19799                    return;
19800                }
19801                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19802                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19803                    // Don't care about who enables an app.
19804                    callingPackage = null;
19805                }
19806                pkgSetting.setEnabled(newState, userId, callingPackage);
19807                // pkgSetting.pkg.mSetEnabled = newState;
19808            } else {
19809                // We're dealing with a component level state change
19810                // First, verify that this is a valid class name.
19811                PackageParser.Package pkg = pkgSetting.pkg;
19812                if (pkg == null || !pkg.hasComponentClassName(className)) {
19813                    if (pkg != null &&
19814                            pkg.applicationInfo.targetSdkVersion >=
19815                                    Build.VERSION_CODES.JELLY_BEAN) {
19816                        throw new IllegalArgumentException("Component class " + className
19817                                + " does not exist in " + packageName);
19818                    } else {
19819                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19820                                + className + " does not exist in " + packageName);
19821                    }
19822                }
19823                switch (newState) {
19824                case COMPONENT_ENABLED_STATE_ENABLED:
19825                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19826                        return;
19827                    }
19828                    break;
19829                case COMPONENT_ENABLED_STATE_DISABLED:
19830                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19831                        return;
19832                    }
19833                    break;
19834                case COMPONENT_ENABLED_STATE_DEFAULT:
19835                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19836                        return;
19837                    }
19838                    break;
19839                default:
19840                    Slog.e(TAG, "Invalid new component state: " + newState);
19841                    return;
19842                }
19843            }
19844            scheduleWritePackageRestrictionsLocked(userId);
19845            updateSequenceNumberLP(packageName, new int[] { userId });
19846            final long callingId = Binder.clearCallingIdentity();
19847            try {
19848                updateInstantAppInstallerLocked();
19849            } finally {
19850                Binder.restoreCallingIdentity(callingId);
19851            }
19852            components = mPendingBroadcasts.get(userId, packageName);
19853            final boolean newPackage = components == null;
19854            if (newPackage) {
19855                components = new ArrayList<String>();
19856            }
19857            if (!components.contains(componentName)) {
19858                components.add(componentName);
19859            }
19860            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19861                sendNow = true;
19862                // Purge entry from pending broadcast list if another one exists already
19863                // since we are sending one right away.
19864                mPendingBroadcasts.remove(userId, packageName);
19865            } else {
19866                if (newPackage) {
19867                    mPendingBroadcasts.put(userId, packageName, components);
19868                }
19869                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19870                    // Schedule a message
19871                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19872                }
19873            }
19874        }
19875
19876        long callingId = Binder.clearCallingIdentity();
19877        try {
19878            if (sendNow) {
19879                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19880                sendPackageChangedBroadcast(packageName,
19881                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19882            }
19883        } finally {
19884            Binder.restoreCallingIdentity(callingId);
19885        }
19886    }
19887
19888    @Override
19889    public void flushPackageRestrictionsAsUser(int userId) {
19890        if (!sUserManager.exists(userId)) {
19891            return;
19892        }
19893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19894                false /* checkShell */, "flushPackageRestrictions");
19895        synchronized (mPackages) {
19896            mSettings.writePackageRestrictionsLPr(userId);
19897            mDirtyUsers.remove(userId);
19898            if (mDirtyUsers.isEmpty()) {
19899                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19900            }
19901        }
19902    }
19903
19904    private void sendPackageChangedBroadcast(String packageName,
19905            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19906        if (DEBUG_INSTALL)
19907            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19908                    + componentNames);
19909        Bundle extras = new Bundle(4);
19910        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19911        String nameList[] = new String[componentNames.size()];
19912        componentNames.toArray(nameList);
19913        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19914        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19915        extras.putInt(Intent.EXTRA_UID, packageUid);
19916        // If this is not reporting a change of the overall package, then only send it
19917        // to registered receivers.  We don't want to launch a swath of apps for every
19918        // little component state change.
19919        final int flags = !componentNames.contains(packageName)
19920                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19921        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19922                new int[] {UserHandle.getUserId(packageUid)});
19923    }
19924
19925    @Override
19926    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19927        if (!sUserManager.exists(userId)) return;
19928        final int uid = Binder.getCallingUid();
19929        final int permission = mContext.checkCallingOrSelfPermission(
19930                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19931        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19932        enforceCrossUserPermission(uid, userId,
19933                true /* requireFullPermission */, true /* checkShell */, "stop package");
19934        // writer
19935        synchronized (mPackages) {
19936            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19937                    allowedByPermission, uid, userId)) {
19938                scheduleWritePackageRestrictionsLocked(userId);
19939            }
19940        }
19941    }
19942
19943    @Override
19944    public String getInstallerPackageName(String packageName) {
19945        // reader
19946        synchronized (mPackages) {
19947            return mSettings.getInstallerPackageNameLPr(packageName);
19948        }
19949    }
19950
19951    public boolean isOrphaned(String packageName) {
19952        // reader
19953        synchronized (mPackages) {
19954            return mSettings.isOrphaned(packageName);
19955        }
19956    }
19957
19958    @Override
19959    public int getApplicationEnabledSetting(String packageName, int userId) {
19960        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19961        int uid = Binder.getCallingUid();
19962        enforceCrossUserPermission(uid, userId,
19963                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19964        // reader
19965        synchronized (mPackages) {
19966            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19967        }
19968    }
19969
19970    @Override
19971    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19972        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19973        int uid = Binder.getCallingUid();
19974        enforceCrossUserPermission(uid, userId,
19975                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19976        // reader
19977        synchronized (mPackages) {
19978            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19979        }
19980    }
19981
19982    @Override
19983    public void enterSafeMode() {
19984        enforceSystemOrRoot("Only the system can request entering safe mode");
19985
19986        if (!mSystemReady) {
19987            mSafeMode = true;
19988        }
19989    }
19990
19991    @Override
19992    public void systemReady() {
19993        mSystemReady = true;
19994
19995        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19996        // disabled after already being started.
19997        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19998                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19999
20000        // Read the compatibilty setting when the system is ready.
20001        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20002                mContext.getContentResolver(),
20003                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20004        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20005        if (DEBUG_SETTINGS) {
20006            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20007        }
20008
20009        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20010
20011        synchronized (mPackages) {
20012            // Verify that all of the preferred activity components actually
20013            // exist.  It is possible for applications to be updated and at
20014            // that point remove a previously declared activity component that
20015            // had been set as a preferred activity.  We try to clean this up
20016            // the next time we encounter that preferred activity, but it is
20017            // possible for the user flow to never be able to return to that
20018            // situation so here we do a sanity check to make sure we haven't
20019            // left any junk around.
20020            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20021            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20022                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20023                removed.clear();
20024                for (PreferredActivity pa : pir.filterSet()) {
20025                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20026                        removed.add(pa);
20027                    }
20028                }
20029                if (removed.size() > 0) {
20030                    for (int r=0; r<removed.size(); r++) {
20031                        PreferredActivity pa = removed.get(r);
20032                        Slog.w(TAG, "Removing dangling preferred activity: "
20033                                + pa.mPref.mComponent);
20034                        pir.removeFilter(pa);
20035                    }
20036                    mSettings.writePackageRestrictionsLPr(
20037                            mSettings.mPreferredActivities.keyAt(i));
20038                }
20039            }
20040
20041            for (int userId : UserManagerService.getInstance().getUserIds()) {
20042                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20043                    grantPermissionsUserIds = ArrayUtils.appendInt(
20044                            grantPermissionsUserIds, userId);
20045                }
20046            }
20047        }
20048        sUserManager.systemReady();
20049
20050        // If we upgraded grant all default permissions before kicking off.
20051        for (int userId : grantPermissionsUserIds) {
20052            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20053        }
20054
20055        // If we did not grant default permissions, we preload from this the
20056        // default permission exceptions lazily to ensure we don't hit the
20057        // disk on a new user creation.
20058        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20059            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20060        }
20061
20062        // Kick off any messages waiting for system ready
20063        if (mPostSystemReadyMessages != null) {
20064            for (Message msg : mPostSystemReadyMessages) {
20065                msg.sendToTarget();
20066            }
20067            mPostSystemReadyMessages = null;
20068        }
20069
20070        // Watch for external volumes that come and go over time
20071        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20072        storage.registerListener(mStorageListener);
20073
20074        mInstallerService.systemReady();
20075        mPackageDexOptimizer.systemReady();
20076
20077        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20078                StorageManagerInternal.class);
20079        StorageManagerInternal.addExternalStoragePolicy(
20080                new StorageManagerInternal.ExternalStorageMountPolicy() {
20081            @Override
20082            public int getMountMode(int uid, String packageName) {
20083                if (Process.isIsolated(uid)) {
20084                    return Zygote.MOUNT_EXTERNAL_NONE;
20085                }
20086                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20087                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20088                }
20089                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20090                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20091                }
20092                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20093                    return Zygote.MOUNT_EXTERNAL_READ;
20094                }
20095                return Zygote.MOUNT_EXTERNAL_WRITE;
20096            }
20097
20098            @Override
20099            public boolean hasExternalStorage(int uid, String packageName) {
20100                return true;
20101            }
20102        });
20103
20104        // Now that we're mostly running, clean up stale users and apps
20105        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20106        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20107
20108        if (mPrivappPermissionsViolations != null) {
20109            Slog.wtf(TAG,"Signature|privileged permissions not in "
20110                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20111            mPrivappPermissionsViolations = null;
20112        }
20113    }
20114
20115    public void waitForAppDataPrepared() {
20116        if (mPrepareAppDataFuture == null) {
20117            return;
20118        }
20119        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20120        mPrepareAppDataFuture = null;
20121    }
20122
20123    @Override
20124    public boolean isSafeMode() {
20125        return mSafeMode;
20126    }
20127
20128    @Override
20129    public boolean hasSystemUidErrors() {
20130        return mHasSystemUidErrors;
20131    }
20132
20133    static String arrayToString(int[] array) {
20134        StringBuffer buf = new StringBuffer(128);
20135        buf.append('[');
20136        if (array != null) {
20137            for (int i=0; i<array.length; i++) {
20138                if (i > 0) buf.append(", ");
20139                buf.append(array[i]);
20140            }
20141        }
20142        buf.append(']');
20143        return buf.toString();
20144    }
20145
20146    static class DumpState {
20147        public static final int DUMP_LIBS = 1 << 0;
20148        public static final int DUMP_FEATURES = 1 << 1;
20149        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20150        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20151        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20152        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20153        public static final int DUMP_PERMISSIONS = 1 << 6;
20154        public static final int DUMP_PACKAGES = 1 << 7;
20155        public static final int DUMP_SHARED_USERS = 1 << 8;
20156        public static final int DUMP_MESSAGES = 1 << 9;
20157        public static final int DUMP_PROVIDERS = 1 << 10;
20158        public static final int DUMP_VERIFIERS = 1 << 11;
20159        public static final int DUMP_PREFERRED = 1 << 12;
20160        public static final int DUMP_PREFERRED_XML = 1 << 13;
20161        public static final int DUMP_KEYSETS = 1 << 14;
20162        public static final int DUMP_VERSION = 1 << 15;
20163        public static final int DUMP_INSTALLS = 1 << 16;
20164        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20165        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20166        public static final int DUMP_FROZEN = 1 << 19;
20167        public static final int DUMP_DEXOPT = 1 << 20;
20168        public static final int DUMP_COMPILER_STATS = 1 << 21;
20169        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20170
20171        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20172
20173        private int mTypes;
20174
20175        private int mOptions;
20176
20177        private boolean mTitlePrinted;
20178
20179        private SharedUserSetting mSharedUser;
20180
20181        public boolean isDumping(int type) {
20182            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20183                return true;
20184            }
20185
20186            return (mTypes & type) != 0;
20187        }
20188
20189        public void setDump(int type) {
20190            mTypes |= type;
20191        }
20192
20193        public boolean isOptionEnabled(int option) {
20194            return (mOptions & option) != 0;
20195        }
20196
20197        public void setOptionEnabled(int option) {
20198            mOptions |= option;
20199        }
20200
20201        public boolean onTitlePrinted() {
20202            final boolean printed = mTitlePrinted;
20203            mTitlePrinted = true;
20204            return printed;
20205        }
20206
20207        public boolean getTitlePrinted() {
20208            return mTitlePrinted;
20209        }
20210
20211        public void setTitlePrinted(boolean enabled) {
20212            mTitlePrinted = enabled;
20213        }
20214
20215        public SharedUserSetting getSharedUser() {
20216            return mSharedUser;
20217        }
20218
20219        public void setSharedUser(SharedUserSetting user) {
20220            mSharedUser = user;
20221        }
20222    }
20223
20224    @Override
20225    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20226            FileDescriptor err, String[] args, ShellCallback callback,
20227            ResultReceiver resultReceiver) {
20228        (new PackageManagerShellCommand(this)).exec(
20229                this, in, out, err, args, callback, resultReceiver);
20230    }
20231
20232    @Override
20233    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20234        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20235
20236        DumpState dumpState = new DumpState();
20237        boolean fullPreferred = false;
20238        boolean checkin = false;
20239
20240        String packageName = null;
20241        ArraySet<String> permissionNames = null;
20242
20243        int opti = 0;
20244        while (opti < args.length) {
20245            String opt = args[opti];
20246            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20247                break;
20248            }
20249            opti++;
20250
20251            if ("-a".equals(opt)) {
20252                // Right now we only know how to print all.
20253            } else if ("-h".equals(opt)) {
20254                pw.println("Package manager dump options:");
20255                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20256                pw.println("    --checkin: dump for a checkin");
20257                pw.println("    -f: print details of intent filters");
20258                pw.println("    -h: print this help");
20259                pw.println("  cmd may be one of:");
20260                pw.println("    l[ibraries]: list known shared libraries");
20261                pw.println("    f[eatures]: list device features");
20262                pw.println("    k[eysets]: print known keysets");
20263                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20264                pw.println("    perm[issions]: dump permissions");
20265                pw.println("    permission [name ...]: dump declaration and use of given permission");
20266                pw.println("    pref[erred]: print preferred package settings");
20267                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20268                pw.println("    prov[iders]: dump content providers");
20269                pw.println("    p[ackages]: dump installed packages");
20270                pw.println("    s[hared-users]: dump shared user IDs");
20271                pw.println("    m[essages]: print collected runtime messages");
20272                pw.println("    v[erifiers]: print package verifier info");
20273                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20274                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20275                pw.println("    version: print database version info");
20276                pw.println("    write: write current settings now");
20277                pw.println("    installs: details about install sessions");
20278                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20279                pw.println("    dexopt: dump dexopt state");
20280                pw.println("    compiler-stats: dump compiler statistics");
20281                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20282                pw.println("    <package.name>: info about given package");
20283                return;
20284            } else if ("--checkin".equals(opt)) {
20285                checkin = true;
20286            } else if ("-f".equals(opt)) {
20287                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20288            } else if ("--proto".equals(opt)) {
20289                dumpProto(fd);
20290                return;
20291            } else {
20292                pw.println("Unknown argument: " + opt + "; use -h for help");
20293            }
20294        }
20295
20296        // Is the caller requesting to dump a particular piece of data?
20297        if (opti < args.length) {
20298            String cmd = args[opti];
20299            opti++;
20300            // Is this a package name?
20301            if ("android".equals(cmd) || cmd.contains(".")) {
20302                packageName = cmd;
20303                // When dumping a single package, we always dump all of its
20304                // filter information since the amount of data will be reasonable.
20305                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20306            } else if ("check-permission".equals(cmd)) {
20307                if (opti >= args.length) {
20308                    pw.println("Error: check-permission missing permission argument");
20309                    return;
20310                }
20311                String perm = args[opti];
20312                opti++;
20313                if (opti >= args.length) {
20314                    pw.println("Error: check-permission missing package argument");
20315                    return;
20316                }
20317
20318                String pkg = args[opti];
20319                opti++;
20320                int user = UserHandle.getUserId(Binder.getCallingUid());
20321                if (opti < args.length) {
20322                    try {
20323                        user = Integer.parseInt(args[opti]);
20324                    } catch (NumberFormatException e) {
20325                        pw.println("Error: check-permission user argument is not a number: "
20326                                + args[opti]);
20327                        return;
20328                    }
20329                }
20330
20331                // Normalize package name to handle renamed packages and static libs
20332                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20333
20334                pw.println(checkPermission(perm, pkg, user));
20335                return;
20336            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20337                dumpState.setDump(DumpState.DUMP_LIBS);
20338            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20339                dumpState.setDump(DumpState.DUMP_FEATURES);
20340            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20341                if (opti >= args.length) {
20342                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20343                            | DumpState.DUMP_SERVICE_RESOLVERS
20344                            | DumpState.DUMP_RECEIVER_RESOLVERS
20345                            | DumpState.DUMP_CONTENT_RESOLVERS);
20346                } else {
20347                    while (opti < args.length) {
20348                        String name = args[opti];
20349                        if ("a".equals(name) || "activity".equals(name)) {
20350                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20351                        } else if ("s".equals(name) || "service".equals(name)) {
20352                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20353                        } else if ("r".equals(name) || "receiver".equals(name)) {
20354                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20355                        } else if ("c".equals(name) || "content".equals(name)) {
20356                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20357                        } else {
20358                            pw.println("Error: unknown resolver table type: " + name);
20359                            return;
20360                        }
20361                        opti++;
20362                    }
20363                }
20364            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20365                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20366            } else if ("permission".equals(cmd)) {
20367                if (opti >= args.length) {
20368                    pw.println("Error: permission requires permission name");
20369                    return;
20370                }
20371                permissionNames = new ArraySet<>();
20372                while (opti < args.length) {
20373                    permissionNames.add(args[opti]);
20374                    opti++;
20375                }
20376                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20377                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20378            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20379                dumpState.setDump(DumpState.DUMP_PREFERRED);
20380            } else if ("preferred-xml".equals(cmd)) {
20381                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20382                if (opti < args.length && "--full".equals(args[opti])) {
20383                    fullPreferred = true;
20384                    opti++;
20385                }
20386            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20387                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20388            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20389                dumpState.setDump(DumpState.DUMP_PACKAGES);
20390            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20391                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20392            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20393                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20394            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20395                dumpState.setDump(DumpState.DUMP_MESSAGES);
20396            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20397                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20398            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20399                    || "intent-filter-verifiers".equals(cmd)) {
20400                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20401            } else if ("version".equals(cmd)) {
20402                dumpState.setDump(DumpState.DUMP_VERSION);
20403            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20404                dumpState.setDump(DumpState.DUMP_KEYSETS);
20405            } else if ("installs".equals(cmd)) {
20406                dumpState.setDump(DumpState.DUMP_INSTALLS);
20407            } else if ("frozen".equals(cmd)) {
20408                dumpState.setDump(DumpState.DUMP_FROZEN);
20409            } else if ("dexopt".equals(cmd)) {
20410                dumpState.setDump(DumpState.DUMP_DEXOPT);
20411            } else if ("compiler-stats".equals(cmd)) {
20412                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20413            } else if ("enabled-overlays".equals(cmd)) {
20414                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20415            } else if ("write".equals(cmd)) {
20416                synchronized (mPackages) {
20417                    mSettings.writeLPr();
20418                    pw.println("Settings written.");
20419                    return;
20420                }
20421            }
20422        }
20423
20424        if (checkin) {
20425            pw.println("vers,1");
20426        }
20427
20428        // reader
20429        synchronized (mPackages) {
20430            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20431                if (!checkin) {
20432                    if (dumpState.onTitlePrinted())
20433                        pw.println();
20434                    pw.println("Database versions:");
20435                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20436                }
20437            }
20438
20439            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20440                if (!checkin) {
20441                    if (dumpState.onTitlePrinted())
20442                        pw.println();
20443                    pw.println("Verifiers:");
20444                    pw.print("  Required: ");
20445                    pw.print(mRequiredVerifierPackage);
20446                    pw.print(" (uid=");
20447                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20448                            UserHandle.USER_SYSTEM));
20449                    pw.println(")");
20450                } else if (mRequiredVerifierPackage != null) {
20451                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20452                    pw.print(",");
20453                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20454                            UserHandle.USER_SYSTEM));
20455                }
20456            }
20457
20458            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20459                    packageName == null) {
20460                if (mIntentFilterVerifierComponent != null) {
20461                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20462                    if (!checkin) {
20463                        if (dumpState.onTitlePrinted())
20464                            pw.println();
20465                        pw.println("Intent Filter Verifier:");
20466                        pw.print("  Using: ");
20467                        pw.print(verifierPackageName);
20468                        pw.print(" (uid=");
20469                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20470                                UserHandle.USER_SYSTEM));
20471                        pw.println(")");
20472                    } else if (verifierPackageName != null) {
20473                        pw.print("ifv,"); pw.print(verifierPackageName);
20474                        pw.print(",");
20475                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20476                                UserHandle.USER_SYSTEM));
20477                    }
20478                } else {
20479                    pw.println();
20480                    pw.println("No Intent Filter Verifier available!");
20481                }
20482            }
20483
20484            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20485                boolean printedHeader = false;
20486                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20487                while (it.hasNext()) {
20488                    String libName = it.next();
20489                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20490                    if (versionedLib == null) {
20491                        continue;
20492                    }
20493                    final int versionCount = versionedLib.size();
20494                    for (int i = 0; i < versionCount; i++) {
20495                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20496                        if (!checkin) {
20497                            if (!printedHeader) {
20498                                if (dumpState.onTitlePrinted())
20499                                    pw.println();
20500                                pw.println("Libraries:");
20501                                printedHeader = true;
20502                            }
20503                            pw.print("  ");
20504                        } else {
20505                            pw.print("lib,");
20506                        }
20507                        pw.print(libEntry.info.getName());
20508                        if (libEntry.info.isStatic()) {
20509                            pw.print(" version=" + libEntry.info.getVersion());
20510                        }
20511                        if (!checkin) {
20512                            pw.print(" -> ");
20513                        }
20514                        if (libEntry.path != null) {
20515                            pw.print(" (jar) ");
20516                            pw.print(libEntry.path);
20517                        } else {
20518                            pw.print(" (apk) ");
20519                            pw.print(libEntry.apk);
20520                        }
20521                        pw.println();
20522                    }
20523                }
20524            }
20525
20526            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20527                if (dumpState.onTitlePrinted())
20528                    pw.println();
20529                if (!checkin) {
20530                    pw.println("Features:");
20531                }
20532
20533                synchronized (mAvailableFeatures) {
20534                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20535                        if (checkin) {
20536                            pw.print("feat,");
20537                            pw.print(feat.name);
20538                            pw.print(",");
20539                            pw.println(feat.version);
20540                        } else {
20541                            pw.print("  ");
20542                            pw.print(feat.name);
20543                            if (feat.version > 0) {
20544                                pw.print(" version=");
20545                                pw.print(feat.version);
20546                            }
20547                            pw.println();
20548                        }
20549                    }
20550                }
20551            }
20552
20553            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20554                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20555                        : "Activity Resolver Table:", "  ", packageName,
20556                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20557                    dumpState.setTitlePrinted(true);
20558                }
20559            }
20560            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20561                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20562                        : "Receiver Resolver Table:", "  ", packageName,
20563                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20564                    dumpState.setTitlePrinted(true);
20565                }
20566            }
20567            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20568                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20569                        : "Service Resolver Table:", "  ", packageName,
20570                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20571                    dumpState.setTitlePrinted(true);
20572                }
20573            }
20574            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20575                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20576                        : "Provider Resolver Table:", "  ", packageName,
20577                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20578                    dumpState.setTitlePrinted(true);
20579                }
20580            }
20581
20582            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20583                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20584                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20585                    int user = mSettings.mPreferredActivities.keyAt(i);
20586                    if (pir.dump(pw,
20587                            dumpState.getTitlePrinted()
20588                                ? "\nPreferred Activities User " + user + ":"
20589                                : "Preferred Activities User " + user + ":", "  ",
20590                            packageName, true, false)) {
20591                        dumpState.setTitlePrinted(true);
20592                    }
20593                }
20594            }
20595
20596            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20597                pw.flush();
20598                FileOutputStream fout = new FileOutputStream(fd);
20599                BufferedOutputStream str = new BufferedOutputStream(fout);
20600                XmlSerializer serializer = new FastXmlSerializer();
20601                try {
20602                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20603                    serializer.startDocument(null, true);
20604                    serializer.setFeature(
20605                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20606                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20607                    serializer.endDocument();
20608                    serializer.flush();
20609                } catch (IllegalArgumentException e) {
20610                    pw.println("Failed writing: " + e);
20611                } catch (IllegalStateException e) {
20612                    pw.println("Failed writing: " + e);
20613                } catch (IOException e) {
20614                    pw.println("Failed writing: " + e);
20615                }
20616            }
20617
20618            if (!checkin
20619                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20620                    && packageName == null) {
20621                pw.println();
20622                int count = mSettings.mPackages.size();
20623                if (count == 0) {
20624                    pw.println("No applications!");
20625                    pw.println();
20626                } else {
20627                    final String prefix = "  ";
20628                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20629                    if (allPackageSettings.size() == 0) {
20630                        pw.println("No domain preferred apps!");
20631                        pw.println();
20632                    } else {
20633                        pw.println("App verification status:");
20634                        pw.println();
20635                        count = 0;
20636                        for (PackageSetting ps : allPackageSettings) {
20637                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20638                            if (ivi == null || ivi.getPackageName() == null) continue;
20639                            pw.println(prefix + "Package: " + ivi.getPackageName());
20640                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20641                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20642                            pw.println();
20643                            count++;
20644                        }
20645                        if (count == 0) {
20646                            pw.println(prefix + "No app verification established.");
20647                            pw.println();
20648                        }
20649                        for (int userId : sUserManager.getUserIds()) {
20650                            pw.println("App linkages for user " + userId + ":");
20651                            pw.println();
20652                            count = 0;
20653                            for (PackageSetting ps : allPackageSettings) {
20654                                final long status = ps.getDomainVerificationStatusForUser(userId);
20655                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20656                                        && !DEBUG_DOMAIN_VERIFICATION) {
20657                                    continue;
20658                                }
20659                                pw.println(prefix + "Package: " + ps.name);
20660                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20661                                String statusStr = IntentFilterVerificationInfo.
20662                                        getStatusStringFromValue(status);
20663                                pw.println(prefix + "Status:  " + statusStr);
20664                                pw.println();
20665                                count++;
20666                            }
20667                            if (count == 0) {
20668                                pw.println(prefix + "No configured app linkages.");
20669                                pw.println();
20670                            }
20671                        }
20672                    }
20673                }
20674            }
20675
20676            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20677                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20678                if (packageName == null && permissionNames == null) {
20679                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20680                        if (iperm == 0) {
20681                            if (dumpState.onTitlePrinted())
20682                                pw.println();
20683                            pw.println("AppOp Permissions:");
20684                        }
20685                        pw.print("  AppOp Permission ");
20686                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20687                        pw.println(":");
20688                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20689                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20690                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20691                        }
20692                    }
20693                }
20694            }
20695
20696            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20697                boolean printedSomething = false;
20698                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20699                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20700                        continue;
20701                    }
20702                    if (!printedSomething) {
20703                        if (dumpState.onTitlePrinted())
20704                            pw.println();
20705                        pw.println("Registered ContentProviders:");
20706                        printedSomething = true;
20707                    }
20708                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20709                    pw.print("    "); pw.println(p.toString());
20710                }
20711                printedSomething = false;
20712                for (Map.Entry<String, PackageParser.Provider> entry :
20713                        mProvidersByAuthority.entrySet()) {
20714                    PackageParser.Provider p = entry.getValue();
20715                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20716                        continue;
20717                    }
20718                    if (!printedSomething) {
20719                        if (dumpState.onTitlePrinted())
20720                            pw.println();
20721                        pw.println("ContentProvider Authorities:");
20722                        printedSomething = true;
20723                    }
20724                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20725                    pw.print("    "); pw.println(p.toString());
20726                    if (p.info != null && p.info.applicationInfo != null) {
20727                        final String appInfo = p.info.applicationInfo.toString();
20728                        pw.print("      applicationInfo="); pw.println(appInfo);
20729                    }
20730                }
20731            }
20732
20733            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20734                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20735            }
20736
20737            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20738                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20739            }
20740
20741            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20742                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20743            }
20744
20745            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20746                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20747            }
20748
20749            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20750                // XXX should handle packageName != null by dumping only install data that
20751                // the given package is involved with.
20752                if (dumpState.onTitlePrinted()) pw.println();
20753                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20754            }
20755
20756            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20757                // XXX should handle packageName != null by dumping only install data that
20758                // the given package is involved with.
20759                if (dumpState.onTitlePrinted()) pw.println();
20760
20761                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20762                ipw.println();
20763                ipw.println("Frozen packages:");
20764                ipw.increaseIndent();
20765                if (mFrozenPackages.size() == 0) {
20766                    ipw.println("(none)");
20767                } else {
20768                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20769                        ipw.println(mFrozenPackages.valueAt(i));
20770                    }
20771                }
20772                ipw.decreaseIndent();
20773            }
20774
20775            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20776                if (dumpState.onTitlePrinted()) pw.println();
20777                dumpDexoptStateLPr(pw, packageName);
20778            }
20779
20780            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20781                if (dumpState.onTitlePrinted()) pw.println();
20782                dumpCompilerStatsLPr(pw, packageName);
20783            }
20784
20785            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20786                if (dumpState.onTitlePrinted()) pw.println();
20787                dumpEnabledOverlaysLPr(pw);
20788            }
20789
20790            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20791                if (dumpState.onTitlePrinted()) pw.println();
20792                mSettings.dumpReadMessagesLPr(pw, dumpState);
20793
20794                pw.println();
20795                pw.println("Package warning messages:");
20796                BufferedReader in = null;
20797                String line = null;
20798                try {
20799                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20800                    while ((line = in.readLine()) != null) {
20801                        if (line.contains("ignored: updated version")) continue;
20802                        pw.println(line);
20803                    }
20804                } catch (IOException ignored) {
20805                } finally {
20806                    IoUtils.closeQuietly(in);
20807                }
20808            }
20809
20810            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20811                BufferedReader in = null;
20812                String line = null;
20813                try {
20814                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20815                    while ((line = in.readLine()) != null) {
20816                        if (line.contains("ignored: updated version")) continue;
20817                        pw.print("msg,");
20818                        pw.println(line);
20819                    }
20820                } catch (IOException ignored) {
20821                } finally {
20822                    IoUtils.closeQuietly(in);
20823                }
20824            }
20825        }
20826    }
20827
20828    private void dumpProto(FileDescriptor fd) {
20829        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20830
20831        synchronized (mPackages) {
20832            final long requiredVerifierPackageToken =
20833                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20834            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20835            proto.write(
20836                    PackageServiceDumpProto.PackageShortProto.UID,
20837                    getPackageUid(
20838                            mRequiredVerifierPackage,
20839                            MATCH_DEBUG_TRIAGED_MISSING,
20840                            UserHandle.USER_SYSTEM));
20841            proto.end(requiredVerifierPackageToken);
20842
20843            if (mIntentFilterVerifierComponent != null) {
20844                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20845                final long verifierPackageToken =
20846                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20847                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20848                proto.write(
20849                        PackageServiceDumpProto.PackageShortProto.UID,
20850                        getPackageUid(
20851                                verifierPackageName,
20852                                MATCH_DEBUG_TRIAGED_MISSING,
20853                                UserHandle.USER_SYSTEM));
20854                proto.end(verifierPackageToken);
20855            }
20856
20857            dumpSharedLibrariesProto(proto);
20858            dumpFeaturesProto(proto);
20859            mSettings.dumpPackagesProto(proto);
20860            mSettings.dumpSharedUsersProto(proto);
20861            dumpMessagesProto(proto);
20862        }
20863        proto.flush();
20864    }
20865
20866    private void dumpMessagesProto(ProtoOutputStream proto) {
20867        BufferedReader in = null;
20868        String line = null;
20869        try {
20870            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20871            while ((line = in.readLine()) != null) {
20872                if (line.contains("ignored: updated version")) continue;
20873                proto.write(PackageServiceDumpProto.MESSAGES, line);
20874            }
20875        } catch (IOException ignored) {
20876        } finally {
20877            IoUtils.closeQuietly(in);
20878        }
20879    }
20880
20881    private void dumpFeaturesProto(ProtoOutputStream proto) {
20882        synchronized (mAvailableFeatures) {
20883            final int count = mAvailableFeatures.size();
20884            for (int i = 0; i < count; i++) {
20885                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20886                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20887                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20888                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20889                proto.end(featureToken);
20890            }
20891        }
20892    }
20893
20894    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20895        final int count = mSharedLibraries.size();
20896        for (int i = 0; i < count; i++) {
20897            final String libName = mSharedLibraries.keyAt(i);
20898            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20899            if (versionedLib == null) {
20900                continue;
20901            }
20902            final int versionCount = versionedLib.size();
20903            for (int j = 0; j < versionCount; j++) {
20904                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20905                final long sharedLibraryToken =
20906                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20907                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20908                final boolean isJar = (libEntry.path != null);
20909                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20910                if (isJar) {
20911                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20912                } else {
20913                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20914                }
20915                proto.end(sharedLibraryToken);
20916            }
20917        }
20918    }
20919
20920    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20921        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20922        ipw.println();
20923        ipw.println("Dexopt state:");
20924        ipw.increaseIndent();
20925        Collection<PackageParser.Package> packages = null;
20926        if (packageName != null) {
20927            PackageParser.Package targetPackage = mPackages.get(packageName);
20928            if (targetPackage != null) {
20929                packages = Collections.singletonList(targetPackage);
20930            } else {
20931                ipw.println("Unable to find package: " + packageName);
20932                return;
20933            }
20934        } else {
20935            packages = mPackages.values();
20936        }
20937
20938        for (PackageParser.Package pkg : packages) {
20939            ipw.println("[" + pkg.packageName + "]");
20940            ipw.increaseIndent();
20941            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20942            ipw.decreaseIndent();
20943        }
20944    }
20945
20946    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20947        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20948        ipw.println();
20949        ipw.println("Compiler stats:");
20950        ipw.increaseIndent();
20951        Collection<PackageParser.Package> packages = null;
20952        if (packageName != null) {
20953            PackageParser.Package targetPackage = mPackages.get(packageName);
20954            if (targetPackage != null) {
20955                packages = Collections.singletonList(targetPackage);
20956            } else {
20957                ipw.println("Unable to find package: " + packageName);
20958                return;
20959            }
20960        } else {
20961            packages = mPackages.values();
20962        }
20963
20964        for (PackageParser.Package pkg : packages) {
20965            ipw.println("[" + pkg.packageName + "]");
20966            ipw.increaseIndent();
20967
20968            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20969            if (stats == null) {
20970                ipw.println("(No recorded stats)");
20971            } else {
20972                stats.dump(ipw);
20973            }
20974            ipw.decreaseIndent();
20975        }
20976    }
20977
20978    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20979        pw.println("Enabled overlay paths:");
20980        final int N = mEnabledOverlayPaths.size();
20981        for (int i = 0; i < N; i++) {
20982            final int userId = mEnabledOverlayPaths.keyAt(i);
20983            pw.println(String.format("    User %d:", userId));
20984            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20985                mEnabledOverlayPaths.valueAt(i);
20986            final int M = userSpecificOverlays.size();
20987            for (int j = 0; j < M; j++) {
20988                final String targetPackageName = userSpecificOverlays.keyAt(j);
20989                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
20990                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
20991            }
20992        }
20993    }
20994
20995    private String dumpDomainString(String packageName) {
20996        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20997                .getList();
20998        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20999
21000        ArraySet<String> result = new ArraySet<>();
21001        if (iviList.size() > 0) {
21002            for (IntentFilterVerificationInfo ivi : iviList) {
21003                for (String host : ivi.getDomains()) {
21004                    result.add(host);
21005                }
21006            }
21007        }
21008        if (filters != null && filters.size() > 0) {
21009            for (IntentFilter filter : filters) {
21010                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21011                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21012                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21013                    result.addAll(filter.getHostsList());
21014                }
21015            }
21016        }
21017
21018        StringBuilder sb = new StringBuilder(result.size() * 16);
21019        for (String domain : result) {
21020            if (sb.length() > 0) sb.append(" ");
21021            sb.append(domain);
21022        }
21023        return sb.toString();
21024    }
21025
21026    // ------- apps on sdcard specific code -------
21027    static final boolean DEBUG_SD_INSTALL = false;
21028
21029    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21030
21031    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21032
21033    private boolean mMediaMounted = false;
21034
21035    static String getEncryptKey() {
21036        try {
21037            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21038                    SD_ENCRYPTION_KEYSTORE_NAME);
21039            if (sdEncKey == null) {
21040                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21041                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21042                if (sdEncKey == null) {
21043                    Slog.e(TAG, "Failed to create encryption keys");
21044                    return null;
21045                }
21046            }
21047            return sdEncKey;
21048        } catch (NoSuchAlgorithmException nsae) {
21049            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21050            return null;
21051        } catch (IOException ioe) {
21052            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21053            return null;
21054        }
21055    }
21056
21057    /*
21058     * Update media status on PackageManager.
21059     */
21060    @Override
21061    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21062        int callingUid = Binder.getCallingUid();
21063        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21064            throw new SecurityException("Media status can only be updated by the system");
21065        }
21066        // reader; this apparently protects mMediaMounted, but should probably
21067        // be a different lock in that case.
21068        synchronized (mPackages) {
21069            Log.i(TAG, "Updating external media status from "
21070                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21071                    + (mediaStatus ? "mounted" : "unmounted"));
21072            if (DEBUG_SD_INSTALL)
21073                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21074                        + ", mMediaMounted=" + mMediaMounted);
21075            if (mediaStatus == mMediaMounted) {
21076                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21077                        : 0, -1);
21078                mHandler.sendMessage(msg);
21079                return;
21080            }
21081            mMediaMounted = mediaStatus;
21082        }
21083        // Queue up an async operation since the package installation may take a
21084        // little while.
21085        mHandler.post(new Runnable() {
21086            public void run() {
21087                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21088            }
21089        });
21090    }
21091
21092    /**
21093     * Called by StorageManagerService when the initial ASECs to scan are available.
21094     * Should block until all the ASEC containers are finished being scanned.
21095     */
21096    public void scanAvailableAsecs() {
21097        updateExternalMediaStatusInner(true, false, false);
21098    }
21099
21100    /*
21101     * Collect information of applications on external media, map them against
21102     * existing containers and update information based on current mount status.
21103     * Please note that we always have to report status if reportStatus has been
21104     * set to true especially when unloading packages.
21105     */
21106    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21107            boolean externalStorage) {
21108        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21109        int[] uidArr = EmptyArray.INT;
21110
21111        final String[] list = PackageHelper.getSecureContainerList();
21112        if (ArrayUtils.isEmpty(list)) {
21113            Log.i(TAG, "No secure containers found");
21114        } else {
21115            // Process list of secure containers and categorize them
21116            // as active or stale based on their package internal state.
21117
21118            // reader
21119            synchronized (mPackages) {
21120                for (String cid : list) {
21121                    // Leave stages untouched for now; installer service owns them
21122                    if (PackageInstallerService.isStageName(cid)) continue;
21123
21124                    if (DEBUG_SD_INSTALL)
21125                        Log.i(TAG, "Processing container " + cid);
21126                    String pkgName = getAsecPackageName(cid);
21127                    if (pkgName == null) {
21128                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21129                        continue;
21130                    }
21131                    if (DEBUG_SD_INSTALL)
21132                        Log.i(TAG, "Looking for pkg : " + pkgName);
21133
21134                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21135                    if (ps == null) {
21136                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21137                        continue;
21138                    }
21139
21140                    /*
21141                     * Skip packages that are not external if we're unmounting
21142                     * external storage.
21143                     */
21144                    if (externalStorage && !isMounted && !isExternal(ps)) {
21145                        continue;
21146                    }
21147
21148                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21149                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21150                    // The package status is changed only if the code path
21151                    // matches between settings and the container id.
21152                    if (ps.codePathString != null
21153                            && ps.codePathString.startsWith(args.getCodePath())) {
21154                        if (DEBUG_SD_INSTALL) {
21155                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21156                                    + " at code path: " + ps.codePathString);
21157                        }
21158
21159                        // We do have a valid package installed on sdcard
21160                        processCids.put(args, ps.codePathString);
21161                        final int uid = ps.appId;
21162                        if (uid != -1) {
21163                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21164                        }
21165                    } else {
21166                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21167                                + ps.codePathString);
21168                    }
21169                }
21170            }
21171
21172            Arrays.sort(uidArr);
21173        }
21174
21175        // Process packages with valid entries.
21176        if (isMounted) {
21177            if (DEBUG_SD_INSTALL)
21178                Log.i(TAG, "Loading packages");
21179            loadMediaPackages(processCids, uidArr, externalStorage);
21180            startCleaningPackages();
21181            mInstallerService.onSecureContainersAvailable();
21182        } else {
21183            if (DEBUG_SD_INSTALL)
21184                Log.i(TAG, "Unloading packages");
21185            unloadMediaPackages(processCids, uidArr, reportStatus);
21186        }
21187    }
21188
21189    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21190            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21191        final int size = infos.size();
21192        final String[] packageNames = new String[size];
21193        final int[] packageUids = new int[size];
21194        for (int i = 0; i < size; i++) {
21195            final ApplicationInfo info = infos.get(i);
21196            packageNames[i] = info.packageName;
21197            packageUids[i] = info.uid;
21198        }
21199        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21200                finishedReceiver);
21201    }
21202
21203    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21204            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21205        sendResourcesChangedBroadcast(mediaStatus, replacing,
21206                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21207    }
21208
21209    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21210            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21211        int size = pkgList.length;
21212        if (size > 0) {
21213            // Send broadcasts here
21214            Bundle extras = new Bundle();
21215            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21216            if (uidArr != null) {
21217                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21218            }
21219            if (replacing) {
21220                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21221            }
21222            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21223                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21224            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21225        }
21226    }
21227
21228   /*
21229     * Look at potentially valid container ids from processCids If package
21230     * information doesn't match the one on record or package scanning fails,
21231     * the cid is added to list of removeCids. We currently don't delete stale
21232     * containers.
21233     */
21234    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21235            boolean externalStorage) {
21236        ArrayList<String> pkgList = new ArrayList<String>();
21237        Set<AsecInstallArgs> keys = processCids.keySet();
21238
21239        for (AsecInstallArgs args : keys) {
21240            String codePath = processCids.get(args);
21241            if (DEBUG_SD_INSTALL)
21242                Log.i(TAG, "Loading container : " + args.cid);
21243            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21244            try {
21245                // Make sure there are no container errors first.
21246                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21247                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21248                            + " when installing from sdcard");
21249                    continue;
21250                }
21251                // Check code path here.
21252                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21253                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21254                            + " does not match one in settings " + codePath);
21255                    continue;
21256                }
21257                // Parse package
21258                int parseFlags = mDefParseFlags;
21259                if (args.isExternalAsec()) {
21260                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21261                }
21262                if (args.isFwdLocked()) {
21263                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21264                }
21265
21266                synchronized (mInstallLock) {
21267                    PackageParser.Package pkg = null;
21268                    try {
21269                        // Sadly we don't know the package name yet to freeze it
21270                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21271                                SCAN_IGNORE_FROZEN, 0, null);
21272                    } catch (PackageManagerException e) {
21273                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21274                    }
21275                    // Scan the package
21276                    if (pkg != null) {
21277                        /*
21278                         * TODO why is the lock being held? doPostInstall is
21279                         * called in other places without the lock. This needs
21280                         * to be straightened out.
21281                         */
21282                        // writer
21283                        synchronized (mPackages) {
21284                            retCode = PackageManager.INSTALL_SUCCEEDED;
21285                            pkgList.add(pkg.packageName);
21286                            // Post process args
21287                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21288                                    pkg.applicationInfo.uid);
21289                        }
21290                    } else {
21291                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21292                    }
21293                }
21294
21295            } finally {
21296                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21297                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21298                }
21299            }
21300        }
21301        // writer
21302        synchronized (mPackages) {
21303            // If the platform SDK has changed since the last time we booted,
21304            // we need to re-grant app permission to catch any new ones that
21305            // appear. This is really a hack, and means that apps can in some
21306            // cases get permissions that the user didn't initially explicitly
21307            // allow... it would be nice to have some better way to handle
21308            // this situation.
21309            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21310                    : mSettings.getInternalVersion();
21311            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21312                    : StorageManager.UUID_PRIVATE_INTERNAL;
21313
21314            int updateFlags = UPDATE_PERMISSIONS_ALL;
21315            if (ver.sdkVersion != mSdkVersion) {
21316                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21317                        + mSdkVersion + "; regranting permissions for external");
21318                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21319            }
21320            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21321
21322            // Yay, everything is now upgraded
21323            ver.forceCurrent();
21324
21325            // can downgrade to reader
21326            // Persist settings
21327            mSettings.writeLPr();
21328        }
21329        // Send a broadcast to let everyone know we are done processing
21330        if (pkgList.size() > 0) {
21331            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21332        }
21333    }
21334
21335   /*
21336     * Utility method to unload a list of specified containers
21337     */
21338    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21339        // Just unmount all valid containers.
21340        for (AsecInstallArgs arg : cidArgs) {
21341            synchronized (mInstallLock) {
21342                arg.doPostDeleteLI(false);
21343           }
21344       }
21345   }
21346
21347    /*
21348     * Unload packages mounted on external media. This involves deleting package
21349     * data from internal structures, sending broadcasts about disabled packages,
21350     * gc'ing to free up references, unmounting all secure containers
21351     * corresponding to packages on external media, and posting a
21352     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21353     * that we always have to post this message if status has been requested no
21354     * matter what.
21355     */
21356    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21357            final boolean reportStatus) {
21358        if (DEBUG_SD_INSTALL)
21359            Log.i(TAG, "unloading media packages");
21360        ArrayList<String> pkgList = new ArrayList<String>();
21361        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21362        final Set<AsecInstallArgs> keys = processCids.keySet();
21363        for (AsecInstallArgs args : keys) {
21364            String pkgName = args.getPackageName();
21365            if (DEBUG_SD_INSTALL)
21366                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21367            // Delete package internally
21368            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21369            synchronized (mInstallLock) {
21370                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21371                final boolean res;
21372                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21373                        "unloadMediaPackages")) {
21374                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21375                            null);
21376                }
21377                if (res) {
21378                    pkgList.add(pkgName);
21379                } else {
21380                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21381                    failedList.add(args);
21382                }
21383            }
21384        }
21385
21386        // reader
21387        synchronized (mPackages) {
21388            // We didn't update the settings after removing each package;
21389            // write them now for all packages.
21390            mSettings.writeLPr();
21391        }
21392
21393        // We have to absolutely send UPDATED_MEDIA_STATUS only
21394        // after confirming that all the receivers processed the ordered
21395        // broadcast when packages get disabled, force a gc to clean things up.
21396        // and unload all the containers.
21397        if (pkgList.size() > 0) {
21398            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21399                    new IIntentReceiver.Stub() {
21400                public void performReceive(Intent intent, int resultCode, String data,
21401                        Bundle extras, boolean ordered, boolean sticky,
21402                        int sendingUser) throws RemoteException {
21403                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21404                            reportStatus ? 1 : 0, 1, keys);
21405                    mHandler.sendMessage(msg);
21406                }
21407            });
21408        } else {
21409            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21410                    keys);
21411            mHandler.sendMessage(msg);
21412        }
21413    }
21414
21415    private void loadPrivatePackages(final VolumeInfo vol) {
21416        mHandler.post(new Runnable() {
21417            @Override
21418            public void run() {
21419                loadPrivatePackagesInner(vol);
21420            }
21421        });
21422    }
21423
21424    private void loadPrivatePackagesInner(VolumeInfo vol) {
21425        final String volumeUuid = vol.fsUuid;
21426        if (TextUtils.isEmpty(volumeUuid)) {
21427            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21428            return;
21429        }
21430
21431        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21432        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21433        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21434
21435        final VersionInfo ver;
21436        final List<PackageSetting> packages;
21437        synchronized (mPackages) {
21438            ver = mSettings.findOrCreateVersion(volumeUuid);
21439            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21440        }
21441
21442        for (PackageSetting ps : packages) {
21443            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21444            synchronized (mInstallLock) {
21445                final PackageParser.Package pkg;
21446                try {
21447                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21448                    loaded.add(pkg.applicationInfo);
21449
21450                } catch (PackageManagerException e) {
21451                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21452                }
21453
21454                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21455                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21456                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21457                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21458                }
21459            }
21460        }
21461
21462        // Reconcile app data for all started/unlocked users
21463        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21464        final UserManager um = mContext.getSystemService(UserManager.class);
21465        UserManagerInternal umInternal = getUserManagerInternal();
21466        for (UserInfo user : um.getUsers()) {
21467            final int flags;
21468            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21469                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21470            } else if (umInternal.isUserRunning(user.id)) {
21471                flags = StorageManager.FLAG_STORAGE_DE;
21472            } else {
21473                continue;
21474            }
21475
21476            try {
21477                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21478                synchronized (mInstallLock) {
21479                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21480                }
21481            } catch (IllegalStateException e) {
21482                // Device was probably ejected, and we'll process that event momentarily
21483                Slog.w(TAG, "Failed to prepare storage: " + e);
21484            }
21485        }
21486
21487        synchronized (mPackages) {
21488            int updateFlags = UPDATE_PERMISSIONS_ALL;
21489            if (ver.sdkVersion != mSdkVersion) {
21490                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21491                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21492                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21493            }
21494            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21495
21496            // Yay, everything is now upgraded
21497            ver.forceCurrent();
21498
21499            mSettings.writeLPr();
21500        }
21501
21502        for (PackageFreezer freezer : freezers) {
21503            freezer.close();
21504        }
21505
21506        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21507        sendResourcesChangedBroadcast(true, false, loaded, null);
21508    }
21509
21510    private void unloadPrivatePackages(final VolumeInfo vol) {
21511        mHandler.post(new Runnable() {
21512            @Override
21513            public void run() {
21514                unloadPrivatePackagesInner(vol);
21515            }
21516        });
21517    }
21518
21519    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21520        final String volumeUuid = vol.fsUuid;
21521        if (TextUtils.isEmpty(volumeUuid)) {
21522            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21523            return;
21524        }
21525
21526        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21527        synchronized (mInstallLock) {
21528        synchronized (mPackages) {
21529            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21530            for (PackageSetting ps : packages) {
21531                if (ps.pkg == null) continue;
21532
21533                final ApplicationInfo info = ps.pkg.applicationInfo;
21534                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21535                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21536
21537                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21538                        "unloadPrivatePackagesInner")) {
21539                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21540                            false, null)) {
21541                        unloaded.add(info);
21542                    } else {
21543                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21544                    }
21545                }
21546
21547                // Try very hard to release any references to this package
21548                // so we don't risk the system server being killed due to
21549                // open FDs
21550                AttributeCache.instance().removePackage(ps.name);
21551            }
21552
21553            mSettings.writeLPr();
21554        }
21555        }
21556
21557        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21558        sendResourcesChangedBroadcast(false, false, unloaded, null);
21559
21560        // Try very hard to release any references to this path so we don't risk
21561        // the system server being killed due to open FDs
21562        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21563
21564        for (int i = 0; i < 3; i++) {
21565            System.gc();
21566            System.runFinalization();
21567        }
21568    }
21569
21570    private void assertPackageKnown(String volumeUuid, String packageName)
21571            throws PackageManagerException {
21572        synchronized (mPackages) {
21573            // Normalize package name to handle renamed packages
21574            packageName = normalizePackageNameLPr(packageName);
21575
21576            final PackageSetting ps = mSettings.mPackages.get(packageName);
21577            if (ps == null) {
21578                throw new PackageManagerException("Package " + packageName + " is unknown");
21579            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21580                throw new PackageManagerException(
21581                        "Package " + packageName + " found on unknown volume " + volumeUuid
21582                                + "; expected volume " + ps.volumeUuid);
21583            }
21584        }
21585    }
21586
21587    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21588            throws PackageManagerException {
21589        synchronized (mPackages) {
21590            // Normalize package name to handle renamed packages
21591            packageName = normalizePackageNameLPr(packageName);
21592
21593            final PackageSetting ps = mSettings.mPackages.get(packageName);
21594            if (ps == null) {
21595                throw new PackageManagerException("Package " + packageName + " is unknown");
21596            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21597                throw new PackageManagerException(
21598                        "Package " + packageName + " found on unknown volume " + volumeUuid
21599                                + "; expected volume " + ps.volumeUuid);
21600            } else if (!ps.getInstalled(userId)) {
21601                throw new PackageManagerException(
21602                        "Package " + packageName + " not installed for user " + userId);
21603            }
21604        }
21605    }
21606
21607    private List<String> collectAbsoluteCodePaths() {
21608        synchronized (mPackages) {
21609            List<String> codePaths = new ArrayList<>();
21610            final int packageCount = mSettings.mPackages.size();
21611            for (int i = 0; i < packageCount; i++) {
21612                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21613                codePaths.add(ps.codePath.getAbsolutePath());
21614            }
21615            return codePaths;
21616        }
21617    }
21618
21619    /**
21620     * Examine all apps present on given mounted volume, and destroy apps that
21621     * aren't expected, either due to uninstallation or reinstallation on
21622     * another volume.
21623     */
21624    private void reconcileApps(String volumeUuid) {
21625        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21626        List<File> filesToDelete = null;
21627
21628        final File[] files = FileUtils.listFilesOrEmpty(
21629                Environment.getDataAppDirectory(volumeUuid));
21630        for (File file : files) {
21631            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21632                    && !PackageInstallerService.isStageName(file.getName());
21633            if (!isPackage) {
21634                // Ignore entries which are not packages
21635                continue;
21636            }
21637
21638            String absolutePath = file.getAbsolutePath();
21639
21640            boolean pathValid = false;
21641            final int absoluteCodePathCount = absoluteCodePaths.size();
21642            for (int i = 0; i < absoluteCodePathCount; i++) {
21643                String absoluteCodePath = absoluteCodePaths.get(i);
21644                if (absolutePath.startsWith(absoluteCodePath)) {
21645                    pathValid = true;
21646                    break;
21647                }
21648            }
21649
21650            if (!pathValid) {
21651                if (filesToDelete == null) {
21652                    filesToDelete = new ArrayList<>();
21653                }
21654                filesToDelete.add(file);
21655            }
21656        }
21657
21658        if (filesToDelete != null) {
21659            final int fileToDeleteCount = filesToDelete.size();
21660            for (int i = 0; i < fileToDeleteCount; i++) {
21661                File fileToDelete = filesToDelete.get(i);
21662                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21663                synchronized (mInstallLock) {
21664                    removeCodePathLI(fileToDelete);
21665                }
21666            }
21667        }
21668    }
21669
21670    /**
21671     * Reconcile all app data for the given user.
21672     * <p>
21673     * Verifies that directories exist and that ownership and labeling is
21674     * correct for all installed apps on all mounted volumes.
21675     */
21676    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21677        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21678        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21679            final String volumeUuid = vol.getFsUuid();
21680            synchronized (mInstallLock) {
21681                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21682            }
21683        }
21684    }
21685
21686    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21687            boolean migrateAppData) {
21688        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21689    }
21690
21691    /**
21692     * Reconcile all app data on given mounted volume.
21693     * <p>
21694     * Destroys app data that isn't expected, either due to uninstallation or
21695     * reinstallation on another volume.
21696     * <p>
21697     * Verifies that directories exist and that ownership and labeling is
21698     * correct for all installed apps.
21699     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21700     */
21701    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21702            boolean migrateAppData, boolean onlyCoreApps) {
21703        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21704                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21705        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21706
21707        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21708        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21709
21710        // First look for stale data that doesn't belong, and check if things
21711        // have changed since we did our last restorecon
21712        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21713            if (StorageManager.isFileEncryptedNativeOrEmulated()
21714                    && !StorageManager.isUserKeyUnlocked(userId)) {
21715                throw new RuntimeException(
21716                        "Yikes, someone asked us to reconcile CE storage while " + userId
21717                                + " was still locked; this would have caused massive data loss!");
21718            }
21719
21720            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21721            for (File file : files) {
21722                final String packageName = file.getName();
21723                try {
21724                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21725                } catch (PackageManagerException e) {
21726                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21727                    try {
21728                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21729                                StorageManager.FLAG_STORAGE_CE, 0);
21730                    } catch (InstallerException e2) {
21731                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21732                    }
21733                }
21734            }
21735        }
21736        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21737            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21738            for (File file : files) {
21739                final String packageName = file.getName();
21740                try {
21741                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21742                } catch (PackageManagerException e) {
21743                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21744                    try {
21745                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21746                                StorageManager.FLAG_STORAGE_DE, 0);
21747                    } catch (InstallerException e2) {
21748                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21749                    }
21750                }
21751            }
21752        }
21753
21754        // Ensure that data directories are ready to roll for all packages
21755        // installed for this volume and user
21756        final List<PackageSetting> packages;
21757        synchronized (mPackages) {
21758            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21759        }
21760        int preparedCount = 0;
21761        for (PackageSetting ps : packages) {
21762            final String packageName = ps.name;
21763            if (ps.pkg == null) {
21764                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21765                // TODO: might be due to legacy ASEC apps; we should circle back
21766                // and reconcile again once they're scanned
21767                continue;
21768            }
21769            // Skip non-core apps if requested
21770            if (onlyCoreApps && !ps.pkg.coreApp) {
21771                result.add(packageName);
21772                continue;
21773            }
21774
21775            if (ps.getInstalled(userId)) {
21776                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21777                preparedCount++;
21778            }
21779        }
21780
21781        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21782        return result;
21783    }
21784
21785    /**
21786     * Prepare app data for the given app just after it was installed or
21787     * upgraded. This method carefully only touches users that it's installed
21788     * for, and it forces a restorecon to handle any seinfo changes.
21789     * <p>
21790     * Verifies that directories exist and that ownership and labeling is
21791     * correct for all installed apps. If there is an ownership mismatch, it
21792     * will try recovering system apps by wiping data; third-party app data is
21793     * left intact.
21794     * <p>
21795     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21796     */
21797    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21798        final PackageSetting ps;
21799        synchronized (mPackages) {
21800            ps = mSettings.mPackages.get(pkg.packageName);
21801            mSettings.writeKernelMappingLPr(ps);
21802        }
21803
21804        final UserManager um = mContext.getSystemService(UserManager.class);
21805        UserManagerInternal umInternal = getUserManagerInternal();
21806        for (UserInfo user : um.getUsers()) {
21807            final int flags;
21808            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21809                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21810            } else if (umInternal.isUserRunning(user.id)) {
21811                flags = StorageManager.FLAG_STORAGE_DE;
21812            } else {
21813                continue;
21814            }
21815
21816            if (ps.getInstalled(user.id)) {
21817                // TODO: when user data is locked, mark that we're still dirty
21818                prepareAppDataLIF(pkg, user.id, flags);
21819            }
21820        }
21821    }
21822
21823    /**
21824     * Prepare app data for the given app.
21825     * <p>
21826     * Verifies that directories exist and that ownership and labeling is
21827     * correct for all installed apps. If there is an ownership mismatch, this
21828     * will try recovering system apps by wiping data; third-party app data is
21829     * left intact.
21830     */
21831    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21832        if (pkg == null) {
21833            Slog.wtf(TAG, "Package was null!", new Throwable());
21834            return;
21835        }
21836        prepareAppDataLeafLIF(pkg, userId, flags);
21837        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21838        for (int i = 0; i < childCount; i++) {
21839            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21840        }
21841    }
21842
21843    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21844            boolean maybeMigrateAppData) {
21845        prepareAppDataLIF(pkg, userId, flags);
21846
21847        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21848            // We may have just shuffled around app data directories, so
21849            // prepare them one more time
21850            prepareAppDataLIF(pkg, userId, flags);
21851        }
21852    }
21853
21854    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21855        if (DEBUG_APP_DATA) {
21856            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21857                    + Integer.toHexString(flags));
21858        }
21859
21860        final String volumeUuid = pkg.volumeUuid;
21861        final String packageName = pkg.packageName;
21862        final ApplicationInfo app = pkg.applicationInfo;
21863        final int appId = UserHandle.getAppId(app.uid);
21864
21865        Preconditions.checkNotNull(app.seInfo);
21866
21867        long ceDataInode = -1;
21868        try {
21869            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21870                    appId, app.seInfo, app.targetSdkVersion);
21871        } catch (InstallerException e) {
21872            if (app.isSystemApp()) {
21873                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21874                        + ", but trying to recover: " + e);
21875                destroyAppDataLeafLIF(pkg, userId, flags);
21876                try {
21877                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21878                            appId, app.seInfo, app.targetSdkVersion);
21879                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21880                } catch (InstallerException e2) {
21881                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21882                }
21883            } else {
21884                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21885            }
21886        }
21887
21888        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21889            // TODO: mark this structure as dirty so we persist it!
21890            synchronized (mPackages) {
21891                final PackageSetting ps = mSettings.mPackages.get(packageName);
21892                if (ps != null) {
21893                    ps.setCeDataInode(ceDataInode, userId);
21894                }
21895            }
21896        }
21897
21898        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21899    }
21900
21901    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21902        if (pkg == null) {
21903            Slog.wtf(TAG, "Package was null!", new Throwable());
21904            return;
21905        }
21906        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21907        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21908        for (int i = 0; i < childCount; i++) {
21909            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21910        }
21911    }
21912
21913    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21914        final String volumeUuid = pkg.volumeUuid;
21915        final String packageName = pkg.packageName;
21916        final ApplicationInfo app = pkg.applicationInfo;
21917
21918        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21919            // Create a native library symlink only if we have native libraries
21920            // and if the native libraries are 32 bit libraries. We do not provide
21921            // this symlink for 64 bit libraries.
21922            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21923                final String nativeLibPath = app.nativeLibraryDir;
21924                try {
21925                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21926                            nativeLibPath, userId);
21927                } catch (InstallerException e) {
21928                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21929                }
21930            }
21931        }
21932    }
21933
21934    /**
21935     * For system apps on non-FBE devices, this method migrates any existing
21936     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21937     * requested by the app.
21938     */
21939    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21940        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21941                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21942            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21943                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21944            try {
21945                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21946                        storageTarget);
21947            } catch (InstallerException e) {
21948                logCriticalInfo(Log.WARN,
21949                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21950            }
21951            return true;
21952        } else {
21953            return false;
21954        }
21955    }
21956
21957    public PackageFreezer freezePackage(String packageName, String killReason) {
21958        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21959    }
21960
21961    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21962        return new PackageFreezer(packageName, userId, killReason);
21963    }
21964
21965    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21966            String killReason) {
21967        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21968    }
21969
21970    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21971            String killReason) {
21972        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21973            return new PackageFreezer();
21974        } else {
21975            return freezePackage(packageName, userId, killReason);
21976        }
21977    }
21978
21979    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21980            String killReason) {
21981        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21982    }
21983
21984    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21985            String killReason) {
21986        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21987            return new PackageFreezer();
21988        } else {
21989            return freezePackage(packageName, userId, killReason);
21990        }
21991    }
21992
21993    /**
21994     * Class that freezes and kills the given package upon creation, and
21995     * unfreezes it upon closing. This is typically used when doing surgery on
21996     * app code/data to prevent the app from running while you're working.
21997     */
21998    private class PackageFreezer implements AutoCloseable {
21999        private final String mPackageName;
22000        private final PackageFreezer[] mChildren;
22001
22002        private final boolean mWeFroze;
22003
22004        private final AtomicBoolean mClosed = new AtomicBoolean();
22005        private final CloseGuard mCloseGuard = CloseGuard.get();
22006
22007        /**
22008         * Create and return a stub freezer that doesn't actually do anything,
22009         * typically used when someone requested
22010         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22011         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22012         */
22013        public PackageFreezer() {
22014            mPackageName = null;
22015            mChildren = null;
22016            mWeFroze = false;
22017            mCloseGuard.open("close");
22018        }
22019
22020        public PackageFreezer(String packageName, int userId, String killReason) {
22021            synchronized (mPackages) {
22022                mPackageName = packageName;
22023                mWeFroze = mFrozenPackages.add(mPackageName);
22024
22025                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22026                if (ps != null) {
22027                    killApplication(ps.name, ps.appId, userId, killReason);
22028                }
22029
22030                final PackageParser.Package p = mPackages.get(packageName);
22031                if (p != null && p.childPackages != null) {
22032                    final int N = p.childPackages.size();
22033                    mChildren = new PackageFreezer[N];
22034                    for (int i = 0; i < N; i++) {
22035                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22036                                userId, killReason);
22037                    }
22038                } else {
22039                    mChildren = null;
22040                }
22041            }
22042            mCloseGuard.open("close");
22043        }
22044
22045        @Override
22046        protected void finalize() throws Throwable {
22047            try {
22048                mCloseGuard.warnIfOpen();
22049                close();
22050            } finally {
22051                super.finalize();
22052            }
22053        }
22054
22055        @Override
22056        public void close() {
22057            mCloseGuard.close();
22058            if (mClosed.compareAndSet(false, true)) {
22059                synchronized (mPackages) {
22060                    if (mWeFroze) {
22061                        mFrozenPackages.remove(mPackageName);
22062                    }
22063
22064                    if (mChildren != null) {
22065                        for (PackageFreezer freezer : mChildren) {
22066                            freezer.close();
22067                        }
22068                    }
22069                }
22070            }
22071        }
22072    }
22073
22074    /**
22075     * Verify that given package is currently frozen.
22076     */
22077    private void checkPackageFrozen(String packageName) {
22078        synchronized (mPackages) {
22079            if (!mFrozenPackages.contains(packageName)) {
22080                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22081            }
22082        }
22083    }
22084
22085    @Override
22086    public int movePackage(final String packageName, final String volumeUuid) {
22087        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22088
22089        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22090        final int moveId = mNextMoveId.getAndIncrement();
22091        mHandler.post(new Runnable() {
22092            @Override
22093            public void run() {
22094                try {
22095                    movePackageInternal(packageName, volumeUuid, moveId, user);
22096                } catch (PackageManagerException e) {
22097                    Slog.w(TAG, "Failed to move " + packageName, e);
22098                    mMoveCallbacks.notifyStatusChanged(moveId,
22099                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22100                }
22101            }
22102        });
22103        return moveId;
22104    }
22105
22106    private void movePackageInternal(final String packageName, final String volumeUuid,
22107            final int moveId, UserHandle user) throws PackageManagerException {
22108        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22109        final PackageManager pm = mContext.getPackageManager();
22110
22111        final boolean currentAsec;
22112        final String currentVolumeUuid;
22113        final File codeFile;
22114        final String installerPackageName;
22115        final String packageAbiOverride;
22116        final int appId;
22117        final String seinfo;
22118        final String label;
22119        final int targetSdkVersion;
22120        final PackageFreezer freezer;
22121        final int[] installedUserIds;
22122
22123        // reader
22124        synchronized (mPackages) {
22125            final PackageParser.Package pkg = mPackages.get(packageName);
22126            final PackageSetting ps = mSettings.mPackages.get(packageName);
22127            if (pkg == null || ps == null) {
22128                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22129            }
22130
22131            if (pkg.applicationInfo.isSystemApp()) {
22132                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22133                        "Cannot move system application");
22134            }
22135
22136            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22137            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22138                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22139            if (isInternalStorage && !allow3rdPartyOnInternal) {
22140                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22141                        "3rd party apps are not allowed on internal storage");
22142            }
22143
22144            if (pkg.applicationInfo.isExternalAsec()) {
22145                currentAsec = true;
22146                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22147            } else if (pkg.applicationInfo.isForwardLocked()) {
22148                currentAsec = true;
22149                currentVolumeUuid = "forward_locked";
22150            } else {
22151                currentAsec = false;
22152                currentVolumeUuid = ps.volumeUuid;
22153
22154                final File probe = new File(pkg.codePath);
22155                final File probeOat = new File(probe, "oat");
22156                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22157                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22158                            "Move only supported for modern cluster style installs");
22159                }
22160            }
22161
22162            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22163                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22164                        "Package already moved to " + volumeUuid);
22165            }
22166            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22167                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22168                        "Device admin cannot be moved");
22169            }
22170
22171            if (mFrozenPackages.contains(packageName)) {
22172                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22173                        "Failed to move already frozen package");
22174            }
22175
22176            codeFile = new File(pkg.codePath);
22177            installerPackageName = ps.installerPackageName;
22178            packageAbiOverride = ps.cpuAbiOverrideString;
22179            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22180            seinfo = pkg.applicationInfo.seInfo;
22181            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22182            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22183            freezer = freezePackage(packageName, "movePackageInternal");
22184            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22185        }
22186
22187        final Bundle extras = new Bundle();
22188        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22189        extras.putString(Intent.EXTRA_TITLE, label);
22190        mMoveCallbacks.notifyCreated(moveId, extras);
22191
22192        int installFlags;
22193        final boolean moveCompleteApp;
22194        final File measurePath;
22195
22196        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22197            installFlags = INSTALL_INTERNAL;
22198            moveCompleteApp = !currentAsec;
22199            measurePath = Environment.getDataAppDirectory(volumeUuid);
22200        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22201            installFlags = INSTALL_EXTERNAL;
22202            moveCompleteApp = false;
22203            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22204        } else {
22205            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22206            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22207                    || !volume.isMountedWritable()) {
22208                freezer.close();
22209                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22210                        "Move location not mounted private volume");
22211            }
22212
22213            Preconditions.checkState(!currentAsec);
22214
22215            installFlags = INSTALL_INTERNAL;
22216            moveCompleteApp = true;
22217            measurePath = Environment.getDataAppDirectory(volumeUuid);
22218        }
22219
22220        final PackageStats stats = new PackageStats(null, -1);
22221        synchronized (mInstaller) {
22222            for (int userId : installedUserIds) {
22223                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22224                    freezer.close();
22225                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22226                            "Failed to measure package size");
22227                }
22228            }
22229        }
22230
22231        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22232                + stats.dataSize);
22233
22234        final long startFreeBytes = measurePath.getFreeSpace();
22235        final long sizeBytes;
22236        if (moveCompleteApp) {
22237            sizeBytes = stats.codeSize + stats.dataSize;
22238        } else {
22239            sizeBytes = stats.codeSize;
22240        }
22241
22242        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22243            freezer.close();
22244            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22245                    "Not enough free space to move");
22246        }
22247
22248        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22249
22250        final CountDownLatch installedLatch = new CountDownLatch(1);
22251        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22252            @Override
22253            public void onUserActionRequired(Intent intent) throws RemoteException {
22254                throw new IllegalStateException();
22255            }
22256
22257            @Override
22258            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22259                    Bundle extras) throws RemoteException {
22260                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22261                        + PackageManager.installStatusToString(returnCode, msg));
22262
22263                installedLatch.countDown();
22264                freezer.close();
22265
22266                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22267                switch (status) {
22268                    case PackageInstaller.STATUS_SUCCESS:
22269                        mMoveCallbacks.notifyStatusChanged(moveId,
22270                                PackageManager.MOVE_SUCCEEDED);
22271                        break;
22272                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22273                        mMoveCallbacks.notifyStatusChanged(moveId,
22274                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22275                        break;
22276                    default:
22277                        mMoveCallbacks.notifyStatusChanged(moveId,
22278                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22279                        break;
22280                }
22281            }
22282        };
22283
22284        final MoveInfo move;
22285        if (moveCompleteApp) {
22286            // Kick off a thread to report progress estimates
22287            new Thread() {
22288                @Override
22289                public void run() {
22290                    while (true) {
22291                        try {
22292                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22293                                break;
22294                            }
22295                        } catch (InterruptedException ignored) {
22296                        }
22297
22298                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22299                        final int progress = 10 + (int) MathUtils.constrain(
22300                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22301                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22302                    }
22303                }
22304            }.start();
22305
22306            final String dataAppName = codeFile.getName();
22307            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22308                    dataAppName, appId, seinfo, targetSdkVersion);
22309        } else {
22310            move = null;
22311        }
22312
22313        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22314
22315        final Message msg = mHandler.obtainMessage(INIT_COPY);
22316        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22317        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22318                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22319                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22320                PackageManager.INSTALL_REASON_UNKNOWN);
22321        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22322        msg.obj = params;
22323
22324        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22325                System.identityHashCode(msg.obj));
22326        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22327                System.identityHashCode(msg.obj));
22328
22329        mHandler.sendMessage(msg);
22330    }
22331
22332    @Override
22333    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22334        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22335
22336        final int realMoveId = mNextMoveId.getAndIncrement();
22337        final Bundle extras = new Bundle();
22338        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22339        mMoveCallbacks.notifyCreated(realMoveId, extras);
22340
22341        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22342            @Override
22343            public void onCreated(int moveId, Bundle extras) {
22344                // Ignored
22345            }
22346
22347            @Override
22348            public void onStatusChanged(int moveId, int status, long estMillis) {
22349                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22350            }
22351        };
22352
22353        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22354        storage.setPrimaryStorageUuid(volumeUuid, callback);
22355        return realMoveId;
22356    }
22357
22358    @Override
22359    public int getMoveStatus(int moveId) {
22360        mContext.enforceCallingOrSelfPermission(
22361                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22362        return mMoveCallbacks.mLastStatus.get(moveId);
22363    }
22364
22365    @Override
22366    public void registerMoveCallback(IPackageMoveObserver callback) {
22367        mContext.enforceCallingOrSelfPermission(
22368                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22369        mMoveCallbacks.register(callback);
22370    }
22371
22372    @Override
22373    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22374        mContext.enforceCallingOrSelfPermission(
22375                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22376        mMoveCallbacks.unregister(callback);
22377    }
22378
22379    @Override
22380    public boolean setInstallLocation(int loc) {
22381        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22382                null);
22383        if (getInstallLocation() == loc) {
22384            return true;
22385        }
22386        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22387                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22388            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22389                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22390            return true;
22391        }
22392        return false;
22393   }
22394
22395    @Override
22396    public int getInstallLocation() {
22397        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22398                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22399                PackageHelper.APP_INSTALL_AUTO);
22400    }
22401
22402    /** Called by UserManagerService */
22403    void cleanUpUser(UserManagerService userManager, int userHandle) {
22404        synchronized (mPackages) {
22405            mDirtyUsers.remove(userHandle);
22406            mUserNeedsBadging.delete(userHandle);
22407            mSettings.removeUserLPw(userHandle);
22408            mPendingBroadcasts.remove(userHandle);
22409            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22410            removeUnusedPackagesLPw(userManager, userHandle);
22411        }
22412    }
22413
22414    /**
22415     * We're removing userHandle and would like to remove any downloaded packages
22416     * that are no longer in use by any other user.
22417     * @param userHandle the user being removed
22418     */
22419    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22420        final boolean DEBUG_CLEAN_APKS = false;
22421        int [] users = userManager.getUserIds();
22422        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22423        while (psit.hasNext()) {
22424            PackageSetting ps = psit.next();
22425            if (ps.pkg == null) {
22426                continue;
22427            }
22428            final String packageName = ps.pkg.packageName;
22429            // Skip over if system app
22430            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22431                continue;
22432            }
22433            if (DEBUG_CLEAN_APKS) {
22434                Slog.i(TAG, "Checking package " + packageName);
22435            }
22436            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22437            if (keep) {
22438                if (DEBUG_CLEAN_APKS) {
22439                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22440                }
22441            } else {
22442                for (int i = 0; i < users.length; i++) {
22443                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22444                        keep = true;
22445                        if (DEBUG_CLEAN_APKS) {
22446                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22447                                    + users[i]);
22448                        }
22449                        break;
22450                    }
22451                }
22452            }
22453            if (!keep) {
22454                if (DEBUG_CLEAN_APKS) {
22455                    Slog.i(TAG, "  Removing package " + packageName);
22456                }
22457                mHandler.post(new Runnable() {
22458                    public void run() {
22459                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22460                                userHandle, 0);
22461                    } //end run
22462                });
22463            }
22464        }
22465    }
22466
22467    /** Called by UserManagerService */
22468    void createNewUser(int userId, String[] disallowedPackages) {
22469        synchronized (mInstallLock) {
22470            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22471        }
22472        synchronized (mPackages) {
22473            scheduleWritePackageRestrictionsLocked(userId);
22474            scheduleWritePackageListLocked(userId);
22475            applyFactoryDefaultBrowserLPw(userId);
22476            primeDomainVerificationsLPw(userId);
22477        }
22478    }
22479
22480    void onNewUserCreated(final int userId) {
22481        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22482        // If permission review for legacy apps is required, we represent
22483        // dagerous permissions for such apps as always granted runtime
22484        // permissions to keep per user flag state whether review is needed.
22485        // Hence, if a new user is added we have to propagate dangerous
22486        // permission grants for these legacy apps.
22487        if (mPermissionReviewRequired) {
22488            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22489                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22490        }
22491    }
22492
22493    @Override
22494    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22495        mContext.enforceCallingOrSelfPermission(
22496                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22497                "Only package verification agents can read the verifier device identity");
22498
22499        synchronized (mPackages) {
22500            return mSettings.getVerifierDeviceIdentityLPw();
22501        }
22502    }
22503
22504    @Override
22505    public void setPermissionEnforced(String permission, boolean enforced) {
22506        // TODO: Now that we no longer change GID for storage, this should to away.
22507        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22508                "setPermissionEnforced");
22509        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22510            synchronized (mPackages) {
22511                if (mSettings.mReadExternalStorageEnforced == null
22512                        || mSettings.mReadExternalStorageEnforced != enforced) {
22513                    mSettings.mReadExternalStorageEnforced = enforced;
22514                    mSettings.writeLPr();
22515                }
22516            }
22517            // kill any non-foreground processes so we restart them and
22518            // grant/revoke the GID.
22519            final IActivityManager am = ActivityManager.getService();
22520            if (am != null) {
22521                final long token = Binder.clearCallingIdentity();
22522                try {
22523                    am.killProcessesBelowForeground("setPermissionEnforcement");
22524                } catch (RemoteException e) {
22525                } finally {
22526                    Binder.restoreCallingIdentity(token);
22527                }
22528            }
22529        } else {
22530            throw new IllegalArgumentException("No selective enforcement for " + permission);
22531        }
22532    }
22533
22534    @Override
22535    @Deprecated
22536    public boolean isPermissionEnforced(String permission) {
22537        return true;
22538    }
22539
22540    @Override
22541    public boolean isStorageLow() {
22542        final long token = Binder.clearCallingIdentity();
22543        try {
22544            final DeviceStorageMonitorInternal
22545                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22546            if (dsm != null) {
22547                return dsm.isMemoryLow();
22548            } else {
22549                return false;
22550            }
22551        } finally {
22552            Binder.restoreCallingIdentity(token);
22553        }
22554    }
22555
22556    @Override
22557    public IPackageInstaller getPackageInstaller() {
22558        return mInstallerService;
22559    }
22560
22561    private boolean userNeedsBadging(int userId) {
22562        int index = mUserNeedsBadging.indexOfKey(userId);
22563        if (index < 0) {
22564            final UserInfo userInfo;
22565            final long token = Binder.clearCallingIdentity();
22566            try {
22567                userInfo = sUserManager.getUserInfo(userId);
22568            } finally {
22569                Binder.restoreCallingIdentity(token);
22570            }
22571            final boolean b;
22572            if (userInfo != null && userInfo.isManagedProfile()) {
22573                b = true;
22574            } else {
22575                b = false;
22576            }
22577            mUserNeedsBadging.put(userId, b);
22578            return b;
22579        }
22580        return mUserNeedsBadging.valueAt(index);
22581    }
22582
22583    @Override
22584    public KeySet getKeySetByAlias(String packageName, String alias) {
22585        if (packageName == null || alias == null) {
22586            return null;
22587        }
22588        synchronized(mPackages) {
22589            final PackageParser.Package pkg = mPackages.get(packageName);
22590            if (pkg == null) {
22591                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22592                throw new IllegalArgumentException("Unknown package: " + packageName);
22593            }
22594            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22595            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22596        }
22597    }
22598
22599    @Override
22600    public KeySet getSigningKeySet(String packageName) {
22601        if (packageName == null) {
22602            return null;
22603        }
22604        synchronized(mPackages) {
22605            final PackageParser.Package pkg = mPackages.get(packageName);
22606            if (pkg == null) {
22607                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22608                throw new IllegalArgumentException("Unknown package: " + packageName);
22609            }
22610            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22611                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22612                throw new SecurityException("May not access signing KeySet of other apps.");
22613            }
22614            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22615            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22616        }
22617    }
22618
22619    @Override
22620    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22621        if (packageName == null || ks == null) {
22622            return false;
22623        }
22624        synchronized(mPackages) {
22625            final PackageParser.Package pkg = mPackages.get(packageName);
22626            if (pkg == null) {
22627                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22628                throw new IllegalArgumentException("Unknown package: " + packageName);
22629            }
22630            IBinder ksh = ks.getToken();
22631            if (ksh instanceof KeySetHandle) {
22632                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22633                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22634            }
22635            return false;
22636        }
22637    }
22638
22639    @Override
22640    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22641        if (packageName == null || ks == null) {
22642            return false;
22643        }
22644        synchronized(mPackages) {
22645            final PackageParser.Package pkg = mPackages.get(packageName);
22646            if (pkg == null) {
22647                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22648                throw new IllegalArgumentException("Unknown package: " + packageName);
22649            }
22650            IBinder ksh = ks.getToken();
22651            if (ksh instanceof KeySetHandle) {
22652                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22653                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22654            }
22655            return false;
22656        }
22657    }
22658
22659    private void deletePackageIfUnusedLPr(final String packageName) {
22660        PackageSetting ps = mSettings.mPackages.get(packageName);
22661        if (ps == null) {
22662            return;
22663        }
22664        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22665            // TODO Implement atomic delete if package is unused
22666            // It is currently possible that the package will be deleted even if it is installed
22667            // after this method returns.
22668            mHandler.post(new Runnable() {
22669                public void run() {
22670                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22671                            0, PackageManager.DELETE_ALL_USERS);
22672                }
22673            });
22674        }
22675    }
22676
22677    /**
22678     * Check and throw if the given before/after packages would be considered a
22679     * downgrade.
22680     */
22681    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22682            throws PackageManagerException {
22683        if (after.versionCode < before.mVersionCode) {
22684            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22685                    "Update version code " + after.versionCode + " is older than current "
22686                    + before.mVersionCode);
22687        } else if (after.versionCode == before.mVersionCode) {
22688            if (after.baseRevisionCode < before.baseRevisionCode) {
22689                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22690                        "Update base revision code " + after.baseRevisionCode
22691                        + " is older than current " + before.baseRevisionCode);
22692            }
22693
22694            if (!ArrayUtils.isEmpty(after.splitNames)) {
22695                for (int i = 0; i < after.splitNames.length; i++) {
22696                    final String splitName = after.splitNames[i];
22697                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22698                    if (j != -1) {
22699                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22700                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22701                                    "Update split " + splitName + " revision code "
22702                                    + after.splitRevisionCodes[i] + " is older than current "
22703                                    + before.splitRevisionCodes[j]);
22704                        }
22705                    }
22706                }
22707            }
22708        }
22709    }
22710
22711    private static class MoveCallbacks extends Handler {
22712        private static final int MSG_CREATED = 1;
22713        private static final int MSG_STATUS_CHANGED = 2;
22714
22715        private final RemoteCallbackList<IPackageMoveObserver>
22716                mCallbacks = new RemoteCallbackList<>();
22717
22718        private final SparseIntArray mLastStatus = new SparseIntArray();
22719
22720        public MoveCallbacks(Looper looper) {
22721            super(looper);
22722        }
22723
22724        public void register(IPackageMoveObserver callback) {
22725            mCallbacks.register(callback);
22726        }
22727
22728        public void unregister(IPackageMoveObserver callback) {
22729            mCallbacks.unregister(callback);
22730        }
22731
22732        @Override
22733        public void handleMessage(Message msg) {
22734            final SomeArgs args = (SomeArgs) msg.obj;
22735            final int n = mCallbacks.beginBroadcast();
22736            for (int i = 0; i < n; i++) {
22737                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22738                try {
22739                    invokeCallback(callback, msg.what, args);
22740                } catch (RemoteException ignored) {
22741                }
22742            }
22743            mCallbacks.finishBroadcast();
22744            args.recycle();
22745        }
22746
22747        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22748                throws RemoteException {
22749            switch (what) {
22750                case MSG_CREATED: {
22751                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22752                    break;
22753                }
22754                case MSG_STATUS_CHANGED: {
22755                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22756                    break;
22757                }
22758            }
22759        }
22760
22761        private void notifyCreated(int moveId, Bundle extras) {
22762            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22763
22764            final SomeArgs args = SomeArgs.obtain();
22765            args.argi1 = moveId;
22766            args.arg2 = extras;
22767            obtainMessage(MSG_CREATED, args).sendToTarget();
22768        }
22769
22770        private void notifyStatusChanged(int moveId, int status) {
22771            notifyStatusChanged(moveId, status, -1);
22772        }
22773
22774        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22775            Slog.v(TAG, "Move " + moveId + " status " + status);
22776
22777            final SomeArgs args = SomeArgs.obtain();
22778            args.argi1 = moveId;
22779            args.argi2 = status;
22780            args.arg3 = estMillis;
22781            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22782
22783            synchronized (mLastStatus) {
22784                mLastStatus.put(moveId, status);
22785            }
22786        }
22787    }
22788
22789    private final static class OnPermissionChangeListeners extends Handler {
22790        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22791
22792        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22793                new RemoteCallbackList<>();
22794
22795        public OnPermissionChangeListeners(Looper looper) {
22796            super(looper);
22797        }
22798
22799        @Override
22800        public void handleMessage(Message msg) {
22801            switch (msg.what) {
22802                case MSG_ON_PERMISSIONS_CHANGED: {
22803                    final int uid = msg.arg1;
22804                    handleOnPermissionsChanged(uid);
22805                } break;
22806            }
22807        }
22808
22809        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22810            mPermissionListeners.register(listener);
22811
22812        }
22813
22814        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22815            mPermissionListeners.unregister(listener);
22816        }
22817
22818        public void onPermissionsChanged(int uid) {
22819            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22820                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22821            }
22822        }
22823
22824        private void handleOnPermissionsChanged(int uid) {
22825            final int count = mPermissionListeners.beginBroadcast();
22826            try {
22827                for (int i = 0; i < count; i++) {
22828                    IOnPermissionsChangeListener callback = mPermissionListeners
22829                            .getBroadcastItem(i);
22830                    try {
22831                        callback.onPermissionsChanged(uid);
22832                    } catch (RemoteException e) {
22833                        Log.e(TAG, "Permission listener is dead", e);
22834                    }
22835                }
22836            } finally {
22837                mPermissionListeners.finishBroadcast();
22838            }
22839        }
22840    }
22841
22842    private class PackageManagerInternalImpl extends PackageManagerInternal {
22843        @Override
22844        public void setLocationPackagesProvider(PackagesProvider provider) {
22845            synchronized (mPackages) {
22846                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22847            }
22848        }
22849
22850        @Override
22851        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22852            synchronized (mPackages) {
22853                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22854            }
22855        }
22856
22857        @Override
22858        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22859            synchronized (mPackages) {
22860                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22861            }
22862        }
22863
22864        @Override
22865        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22866            synchronized (mPackages) {
22867                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22868            }
22869        }
22870
22871        @Override
22872        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22873            synchronized (mPackages) {
22874                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22875            }
22876        }
22877
22878        @Override
22879        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22880            synchronized (mPackages) {
22881                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22882            }
22883        }
22884
22885        @Override
22886        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22887            synchronized (mPackages) {
22888                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22889                        packageName, userId);
22890            }
22891        }
22892
22893        @Override
22894        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22895            synchronized (mPackages) {
22896                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22897                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22898                        packageName, userId);
22899            }
22900        }
22901
22902        @Override
22903        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22904            synchronized (mPackages) {
22905                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22906                        packageName, userId);
22907            }
22908        }
22909
22910        @Override
22911        public void setKeepUninstalledPackages(final List<String> packageList) {
22912            Preconditions.checkNotNull(packageList);
22913            List<String> removedFromList = null;
22914            synchronized (mPackages) {
22915                if (mKeepUninstalledPackages != null) {
22916                    final int packagesCount = mKeepUninstalledPackages.size();
22917                    for (int i = 0; i < packagesCount; i++) {
22918                        String oldPackage = mKeepUninstalledPackages.get(i);
22919                        if (packageList != null && packageList.contains(oldPackage)) {
22920                            continue;
22921                        }
22922                        if (removedFromList == null) {
22923                            removedFromList = new ArrayList<>();
22924                        }
22925                        removedFromList.add(oldPackage);
22926                    }
22927                }
22928                mKeepUninstalledPackages = new ArrayList<>(packageList);
22929                if (removedFromList != null) {
22930                    final int removedCount = removedFromList.size();
22931                    for (int i = 0; i < removedCount; i++) {
22932                        deletePackageIfUnusedLPr(removedFromList.get(i));
22933                    }
22934                }
22935            }
22936        }
22937
22938        @Override
22939        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22940            synchronized (mPackages) {
22941                // If we do not support permission review, done.
22942                if (!mPermissionReviewRequired) {
22943                    return false;
22944                }
22945
22946                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22947                if (packageSetting == null) {
22948                    return false;
22949                }
22950
22951                // Permission review applies only to apps not supporting the new permission model.
22952                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22953                    return false;
22954                }
22955
22956                // Legacy apps have the permission and get user consent on launch.
22957                PermissionsState permissionsState = packageSetting.getPermissionsState();
22958                return permissionsState.isPermissionReviewRequired(userId);
22959            }
22960        }
22961
22962        @Override
22963        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22964            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22965        }
22966
22967        @Override
22968        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22969                int userId) {
22970            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22971        }
22972
22973        @Override
22974        public void setDeviceAndProfileOwnerPackages(
22975                int deviceOwnerUserId, String deviceOwnerPackage,
22976                SparseArray<String> profileOwnerPackages) {
22977            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22978                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22979        }
22980
22981        @Override
22982        public boolean isPackageDataProtected(int userId, String packageName) {
22983            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22984        }
22985
22986        @Override
22987        public boolean isPackageEphemeral(int userId, String packageName) {
22988            synchronized (mPackages) {
22989                final PackageSetting ps = mSettings.mPackages.get(packageName);
22990                return ps != null ? ps.getInstantApp(userId) : false;
22991            }
22992        }
22993
22994        @Override
22995        public boolean wasPackageEverLaunched(String packageName, int userId) {
22996            synchronized (mPackages) {
22997                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22998            }
22999        }
23000
23001        @Override
23002        public void grantRuntimePermission(String packageName, String name, int userId,
23003                boolean overridePolicy) {
23004            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23005                    overridePolicy);
23006        }
23007
23008        @Override
23009        public void revokeRuntimePermission(String packageName, String name, int userId,
23010                boolean overridePolicy) {
23011            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23012                    overridePolicy);
23013        }
23014
23015        @Override
23016        public String getNameForUid(int uid) {
23017            return PackageManagerService.this.getNameForUid(uid);
23018        }
23019
23020        @Override
23021        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23022                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23023            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23024                    responseObj, origIntent, resolvedType, callingPackage, userId);
23025        }
23026
23027        @Override
23028        public void grantEphemeralAccess(int userId, Intent intent,
23029                int targetAppId, int ephemeralAppId) {
23030            synchronized (mPackages) {
23031                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23032                        targetAppId, ephemeralAppId);
23033            }
23034        }
23035
23036        @Override
23037        public boolean isInstantAppInstallerComponent(ComponentName component) {
23038            synchronized (mPackages) {
23039                return component != null && component.equals(mInstantAppInstallerComponent);
23040            }
23041        }
23042
23043        @Override
23044        public void pruneInstantApps() {
23045            synchronized (mPackages) {
23046                mInstantAppRegistry.pruneInstantAppsLPw();
23047            }
23048        }
23049
23050        @Override
23051        public String getSetupWizardPackageName() {
23052            return mSetupWizardPackage;
23053        }
23054
23055        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23056            if (policy != null) {
23057                mExternalSourcesPolicy = policy;
23058            }
23059        }
23060
23061        @Override
23062        public boolean isPackagePersistent(String packageName) {
23063            synchronized (mPackages) {
23064                PackageParser.Package pkg = mPackages.get(packageName);
23065                return pkg != null
23066                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23067                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23068                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23069                        : false;
23070            }
23071        }
23072
23073        @Override
23074        public List<PackageInfo> getOverlayPackages(int userId) {
23075            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23076            synchronized (mPackages) {
23077                for (PackageParser.Package p : mPackages.values()) {
23078                    if (p.mOverlayTarget != null) {
23079                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23080                        if (pkg != null) {
23081                            overlayPackages.add(pkg);
23082                        }
23083                    }
23084                }
23085            }
23086            return overlayPackages;
23087        }
23088
23089        @Override
23090        public List<String> getTargetPackageNames(int userId) {
23091            List<String> targetPackages = new ArrayList<>();
23092            synchronized (mPackages) {
23093                for (PackageParser.Package p : mPackages.values()) {
23094                    if (p.mOverlayTarget == null) {
23095                        targetPackages.add(p.packageName);
23096                    }
23097                }
23098            }
23099            return targetPackages;
23100        }
23101
23102        @Override
23103        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23104                @Nullable List<String> overlayPackageNames) {
23105            synchronized (mPackages) {
23106                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23107                    Slog.e(TAG, "failed to find package " + targetPackageName);
23108                    return false;
23109                }
23110
23111                ArrayList<String> paths = null;
23112                if (overlayPackageNames != null) {
23113                    final int N = overlayPackageNames.size();
23114                    paths = new ArrayList<>(N);
23115                    for (int i = 0; i < N; i++) {
23116                        final String packageName = overlayPackageNames.get(i);
23117                        final PackageParser.Package pkg = mPackages.get(packageName);
23118                        if (pkg == null) {
23119                            Slog.e(TAG, "failed to find package " + packageName);
23120                            return false;
23121                        }
23122                        paths.add(pkg.baseCodePath);
23123                    }
23124                }
23125
23126                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23127                    mEnabledOverlayPaths.get(userId);
23128                if (userSpecificOverlays == null) {
23129                    userSpecificOverlays = new ArrayMap<>();
23130                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23131                }
23132
23133                if (paths != null && paths.size() > 0) {
23134                    userSpecificOverlays.put(targetPackageName, paths);
23135                } else {
23136                    userSpecificOverlays.remove(targetPackageName);
23137                }
23138                return true;
23139            }
23140        }
23141
23142        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23143                int flags, int userId) {
23144            return resolveIntentInternal(
23145                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23146        }
23147
23148
23149        @Override
23150        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23151            synchronized (mPackages) {
23152                mIsolatedOwners.put(isolatedUid, ownerUid);
23153            }
23154        }
23155
23156        @Override
23157        public void removeIsolatedUid(int isolatedUid) {
23158            synchronized (mPackages) {
23159                mIsolatedOwners.delete(isolatedUid);
23160            }
23161        }
23162    }
23163
23164    @Override
23165    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23166        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23167        synchronized (mPackages) {
23168            final long identity = Binder.clearCallingIdentity();
23169            try {
23170                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23171                        packageNames, userId);
23172            } finally {
23173                Binder.restoreCallingIdentity(identity);
23174            }
23175        }
23176    }
23177
23178    @Override
23179    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23180        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23181        synchronized (mPackages) {
23182            final long identity = Binder.clearCallingIdentity();
23183            try {
23184                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23185                        packageNames, userId);
23186            } finally {
23187                Binder.restoreCallingIdentity(identity);
23188            }
23189        }
23190    }
23191
23192    private static void enforceSystemOrPhoneCaller(String tag) {
23193        int callingUid = Binder.getCallingUid();
23194        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23195            throw new SecurityException(
23196                    "Cannot call " + tag + " from UID " + callingUid);
23197        }
23198    }
23199
23200    boolean isHistoricalPackageUsageAvailable() {
23201        return mPackageUsage.isHistoricalPackageUsageAvailable();
23202    }
23203
23204    /**
23205     * Return a <b>copy</b> of the collection of packages known to the package manager.
23206     * @return A copy of the values of mPackages.
23207     */
23208    Collection<PackageParser.Package> getPackages() {
23209        synchronized (mPackages) {
23210            return new ArrayList<>(mPackages.values());
23211        }
23212    }
23213
23214    /**
23215     * Logs process start information (including base APK hash) to the security log.
23216     * @hide
23217     */
23218    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23219            String apkFile, int pid) {
23220        if (!SecurityLog.isLoggingEnabled()) {
23221            return;
23222        }
23223        Bundle data = new Bundle();
23224        data.putLong("startTimestamp", System.currentTimeMillis());
23225        data.putString("processName", processName);
23226        data.putInt("uid", uid);
23227        data.putString("seinfo", seinfo);
23228        data.putString("apkFile", apkFile);
23229        data.putInt("pid", pid);
23230        Message msg = mProcessLoggingHandler.obtainMessage(
23231                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23232        msg.setData(data);
23233        mProcessLoggingHandler.sendMessage(msg);
23234    }
23235
23236    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23237        return mCompilerStats.getPackageStats(pkgName);
23238    }
23239
23240    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23241        return getOrCreateCompilerPackageStats(pkg.packageName);
23242    }
23243
23244    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23245        return mCompilerStats.getOrCreatePackageStats(pkgName);
23246    }
23247
23248    public void deleteCompilerPackageStats(String pkgName) {
23249        mCompilerStats.deletePackageStats(pkgName);
23250    }
23251
23252    @Override
23253    public int getInstallReason(String packageName, int userId) {
23254        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23255                true /* requireFullPermission */, false /* checkShell */,
23256                "get install reason");
23257        synchronized (mPackages) {
23258            final PackageSetting ps = mSettings.mPackages.get(packageName);
23259            if (ps != null) {
23260                return ps.getInstallReason(userId);
23261            }
23262        }
23263        return PackageManager.INSTALL_REASON_UNKNOWN;
23264    }
23265
23266    @Override
23267    public boolean canRequestPackageInstalls(String packageName, int userId) {
23268        int callingUid = Binder.getCallingUid();
23269        int uid = getPackageUid(packageName, 0, userId);
23270        if (callingUid != uid && callingUid != Process.ROOT_UID
23271                && callingUid != Process.SYSTEM_UID) {
23272            throw new SecurityException(
23273                    "Caller uid " + callingUid + " does not own package " + packageName);
23274        }
23275        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23276        if (info == null) {
23277            return false;
23278        }
23279        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23280            throw new UnsupportedOperationException(
23281                    "Operation only supported on apps targeting Android O or higher");
23282        }
23283        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23284        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23285        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23286            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23287        }
23288        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23289            return false;
23290        }
23291        if (mExternalSourcesPolicy != null) {
23292            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23293            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23294                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23295            }
23296        }
23297        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23298    }
23299
23300    @Override
23301    public ComponentName getInstantAppResolverSettingsComponent() {
23302        return mInstantAppResolverSettingsComponent;
23303    }
23304}
23305