PackageManagerService.java revision cc576cfbb4e3d63b5c01e1ad881f0b2c33d9bf28
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.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104
105import android.Manifest;
106import android.annotation.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.ChangedPackages;
129import android.content.pm.ComponentInfo;
130import android.content.pm.InstantAppRequest;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppResolveInfo;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.database.ContentObserver;
175import android.graphics.Bitmap;
176import android.hardware.display.DisplayManager;
177import android.net.Uri;
178import android.os.Binder;
179import android.os.Build;
180import android.os.Bundle;
181import android.os.Debug;
182import android.os.Environment;
183import android.os.Environment.UserEnvironment;
184import android.os.FileUtils;
185import android.os.Handler;
186import android.os.IBinder;
187import android.os.Looper;
188import android.os.Message;
189import android.os.Parcel;
190import android.os.ParcelFileDescriptor;
191import android.os.PatternMatcher;
192import android.os.Process;
193import android.os.RemoteCallbackList;
194import android.os.RemoteException;
195import android.os.ResultReceiver;
196import android.os.SELinux;
197import android.os.ServiceManager;
198import android.os.ShellCallback;
199import android.os.SystemClock;
200import android.os.SystemProperties;
201import android.os.Trace;
202import android.os.UserHandle;
203import android.os.UserManager;
204import android.os.UserManagerInternal;
205import android.os.storage.IStorageManager;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.StorageManagerInternal;
209import android.os.storage.VolumeInfo;
210import android.os.storage.VolumeRecord;
211import android.provider.Settings.Global;
212import android.provider.Settings.Secure;
213import android.security.KeyStore;
214import android.security.SystemKeyStore;
215import android.service.pm.PackageServiceDumpProto;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.BootTimingsTraceLog;
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.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileOutputStream;
301import java.io.FileReader;
302import java.io.FilenameFilter;
303import java.io.IOException;
304import java.io.PrintWriter;
305import java.nio.charset.StandardCharsets;
306import java.security.DigestInputStream;
307import java.security.MessageDigest;
308import java.security.NoSuchAlgorithmException;
309import java.security.PublicKey;
310import java.security.SecureRandom;
311import java.security.cert.Certificate;
312import java.security.cert.CertificateEncodingException;
313import java.security.cert.CertificateException;
314import java.text.SimpleDateFormat;
315import java.util.ArrayList;
316import java.util.Arrays;
317import java.util.Collection;
318import java.util.Collections;
319import java.util.Comparator;
320import java.util.Date;
321import java.util.HashMap;
322import java.util.HashSet;
323import java.util.Iterator;
324import java.util.List;
325import java.util.Map;
326import java.util.Objects;
327import java.util.Set;
328import java.util.concurrent.CountDownLatch;
329import java.util.concurrent.Future;
330import java.util.concurrent.TimeUnit;
331import java.util.concurrent.atomic.AtomicBoolean;
332import java.util.concurrent.atomic.AtomicInteger;
333
334/**
335 * Keep track of all those APKs everywhere.
336 * <p>
337 * Internally there are two important locks:
338 * <ul>
339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
340 * and other related state. It is a fine-grained lock that should only be held
341 * momentarily, as it's one of the most contended locks in the system.
342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
343 * operations typically involve heavy lifting of application data on disk. Since
344 * {@code installd} is single-threaded, and it's operations can often be slow,
345 * this lock should never be acquired while already holding {@link #mPackages}.
346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
347 * holding {@link #mInstallLock}.
348 * </ul>
349 * Many internal methods rely on the caller to hold the appropriate locks, and
350 * this contract is expressed through method name suffixes:
351 * <ul>
352 * <li>fooLI(): the caller must hold {@link #mInstallLock}
353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
354 * being modified must be frozen
355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
357 * </ul>
358 * <p>
359 * Because this class is very central to the platform's security; please run all
360 * CTS and unit tests whenever making modifications:
361 *
362 * <pre>
363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
365 * </pre>
366 */
367public class PackageManagerService extends IPackageManager.Stub
368        implements PackageSender {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean HIDE_EPHEMERAL_APIS = false;
399
400    private static final boolean ENABLE_FREE_CACHE_V2 =
401            SystemProperties.getBoolean("fw.free_cache_v2", true);
402
403    private static final int RADIO_UID = Process.PHONE_UID;
404    private static final int LOG_UID = Process.LOG_UID;
405    private static final int NFC_UID = Process.NFC_UID;
406    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
407    private static final int SHELL_UID = Process.SHELL_UID;
408
409    // Cap the size of permission trees that 3rd party apps can define
410    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
411
412    // Suffix used during package installation when copying/moving
413    // package apks to install directory.
414    private static final String INSTALL_PACKAGE_SUFFIX = "-";
415
416    static final int SCAN_NO_DEX = 1<<1;
417    static final int SCAN_FORCE_DEX = 1<<2;
418    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
419    static final int SCAN_NEW_INSTALL = 1<<4;
420    static final int SCAN_UPDATE_TIME = 1<<5;
421    static final int SCAN_BOOTING = 1<<6;
422    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
423    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
424    static final int SCAN_REPLACING = 1<<9;
425    static final int SCAN_REQUIRE_KNOWN = 1<<10;
426    static final int SCAN_MOVE = 1<<11;
427    static final int SCAN_INITIAL = 1<<12;
428    static final int SCAN_CHECK_ONLY = 1<<13;
429    static final int SCAN_DONT_KILL_APP = 1<<14;
430    static final int SCAN_IGNORE_FROZEN = 1<<15;
431    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
432    static final int SCAN_AS_INSTANT_APP = 1<<17;
433    static final int SCAN_AS_FULL_APP = 1<<18;
434    /** Should not be with the scan flags */
435    static final int FLAGS_REMOVE_CHATTY = 1<<31;
436
437    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
438
439    private static final int[] EMPTY_INT_ARRAY = new int[0];
440
441    /**
442     * Timeout (in milliseconds) after which the watchdog should declare that
443     * our handler thread is wedged.  The usual default for such things is one
444     * minute but we sometimes do very lengthy I/O operations on this thread,
445     * such as installing multi-gigabyte applications, so ours needs to be longer.
446     */
447    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
448
449    /**
450     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
451     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
452     * settings entry if available, otherwise we use the hardcoded default.  If it's been
453     * more than this long since the last fstrim, we force one during the boot sequence.
454     *
455     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
456     * one gets run at the next available charging+idle time.  This final mandatory
457     * no-fstrim check kicks in only of the other scheduling criteria is never met.
458     */
459    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
460
461    /**
462     * Whether verification is enabled by default.
463     */
464    private static final boolean DEFAULT_VERIFY_ENABLE = true;
465
466    /**
467     * The default maximum time to wait for the verification agent to return in
468     * milliseconds.
469     */
470    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
471
472    /**
473     * The default response for package verification timeout.
474     *
475     * This can be either PackageManager.VERIFICATION_ALLOW or
476     * PackageManager.VERIFICATION_REJECT.
477     */
478    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
479
480    static final String PLATFORM_PACKAGE_NAME = "android";
481
482    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
483
484    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
485            DEFAULT_CONTAINER_PACKAGE,
486            "com.android.defcontainer.DefaultContainerService");
487
488    private static final String KILL_APP_REASON_GIDS_CHANGED =
489            "permission grant or revoke changed gids";
490
491    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
492            "permissions revoked";
493
494    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
495
496    private static final String PACKAGE_SCHEME = "package";
497
498    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
499
500    /** Permission grant: not grant the permission. */
501    private static final int GRANT_DENIED = 1;
502
503    /** Permission grant: grant the permission as an install permission. */
504    private static final int GRANT_INSTALL = 2;
505
506    /** Permission grant: grant the permission as a runtime one. */
507    private static final int GRANT_RUNTIME = 3;
508
509    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
510    private static final int GRANT_UPGRADE = 4;
511
512    /** Canonical intent used to identify what counts as a "web browser" app */
513    private static final Intent sBrowserIntent;
514    static {
515        sBrowserIntent = new Intent();
516        sBrowserIntent.setAction(Intent.ACTION_VIEW);
517        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
518        sBrowserIntent.setData(Uri.parse("http:"));
519    }
520
521    /**
522     * The set of all protected actions [i.e. those actions for which a high priority
523     * intent filter is disallowed].
524     */
525    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
526    static {
527        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
528        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
530        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
531    }
532
533    // Compilation reasons.
534    public static final int REASON_FIRST_BOOT = 0;
535    public static final int REASON_BOOT = 1;
536    public static final int REASON_INSTALL = 2;
537    public static final int REASON_BACKGROUND_DEXOPT = 3;
538    public static final int REASON_AB_OTA = 4;
539    public static final int REASON_FORCED_DEXOPT = 5;
540
541    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
542
543    /** All dangerous permission names in the same order as the events in MetricsEvent */
544    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
545            Manifest.permission.READ_CALENDAR,
546            Manifest.permission.WRITE_CALENDAR,
547            Manifest.permission.CAMERA,
548            Manifest.permission.READ_CONTACTS,
549            Manifest.permission.WRITE_CONTACTS,
550            Manifest.permission.GET_ACCOUNTS,
551            Manifest.permission.ACCESS_FINE_LOCATION,
552            Manifest.permission.ACCESS_COARSE_LOCATION,
553            Manifest.permission.RECORD_AUDIO,
554            Manifest.permission.READ_PHONE_STATE,
555            Manifest.permission.CALL_PHONE,
556            Manifest.permission.READ_CALL_LOG,
557            Manifest.permission.WRITE_CALL_LOG,
558            Manifest.permission.ADD_VOICEMAIL,
559            Manifest.permission.USE_SIP,
560            Manifest.permission.PROCESS_OUTGOING_CALLS,
561            Manifest.permission.READ_CELL_BROADCASTS,
562            Manifest.permission.BODY_SENSORS,
563            Manifest.permission.SEND_SMS,
564            Manifest.permission.RECEIVE_SMS,
565            Manifest.permission.READ_SMS,
566            Manifest.permission.RECEIVE_WAP_PUSH,
567            Manifest.permission.RECEIVE_MMS,
568            Manifest.permission.READ_EXTERNAL_STORAGE,
569            Manifest.permission.WRITE_EXTERNAL_STORAGE,
570            Manifest.permission.READ_PHONE_NUMBERS,
571            Manifest.permission.ANSWER_PHONE_CALLS);
572
573
574    /**
575     * Version number for the package parser cache. Increment this whenever the format or
576     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
577     */
578    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
579
580    /**
581     * Whether the package parser cache is enabled.
582     */
583    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
584
585    final ServiceThread mHandlerThread;
586
587    final PackageHandler mHandler;
588
589    private final ProcessLoggingHandler mProcessLoggingHandler;
590
591    /**
592     * Messages for {@link #mHandler} that need to wait for system ready before
593     * being dispatched.
594     */
595    private ArrayList<Message> mPostSystemReadyMessages;
596
597    final int mSdkVersion = Build.VERSION.SDK_INT;
598
599    final Context mContext;
600    final boolean mFactoryTest;
601    final boolean mOnlyCore;
602    final DisplayMetrics mMetrics;
603    final int mDefParseFlags;
604    final String[] mSeparateProcesses;
605    final boolean mIsUpgrade;
606    final boolean mIsPreNUpgrade;
607    final boolean mIsPreNMR1Upgrade;
608
609    // Have we told the Activity Manager to whitelist the default container service by uid yet?
610    @GuardedBy("mPackages")
611    boolean mDefaultContainerWhitelisted = false;
612
613    @GuardedBy("mPackages")
614    private boolean mDexOptDialogShown;
615
616    /** The location for ASEC container files on internal storage. */
617    final String mAsecInternalPath;
618
619    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620    // LOCK HELD.  Can be called with mInstallLock held.
621    @GuardedBy("mInstallLock")
622    final Installer mInstaller;
623
624    /** Directory where installed third-party apps stored */
625    final File mAppInstallDir;
626
627    /**
628     * Directory to which applications installed internally have their
629     * 32 bit native libraries copied.
630     */
631    private File mAppLib32InstallDir;
632
633    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
634    // apps.
635    final File mDrmAppPrivateInstallDir;
636
637    // ----------------------------------------------------------------
638
639    // Lock for state used when installing and doing other long running
640    // operations.  Methods that must be called with this lock held have
641    // the suffix "LI".
642    final Object mInstallLock = new Object();
643
644    // ----------------------------------------------------------------
645
646    // Keys are String (package name), values are Package.  This also serves
647    // as the lock for the global state.  Methods that must be called with
648    // this lock held have the prefix "LP".
649    @GuardedBy("mPackages")
650    final ArrayMap<String, PackageParser.Package> mPackages =
651            new ArrayMap<String, PackageParser.Package>();
652
653    final ArrayMap<String, Set<String>> mKnownCodebase =
654            new ArrayMap<String, Set<String>>();
655
656    // Keys are isolated uids and values are the uid of the application
657    // that created the isolated proccess.
658    @GuardedBy("mPackages")
659    final SparseIntArray mIsolatedOwners = new SparseIntArray();
660
661    // List of APK paths to load for each user and package. This data is never
662    // persisted by the package manager. Instead, the overlay manager will
663    // ensure the data is up-to-date in runtime.
664    @GuardedBy("mPackages")
665    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
666        new SparseArray<ArrayMap<String, ArrayList<String>>>();
667
668    /**
669     * Tracks new system packages [received in an OTA] that we expect to
670     * find updated user-installed versions. Keys are package name, values
671     * are package location.
672     */
673    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
674    /**
675     * Tracks high priority intent filters for protected actions. During boot, certain
676     * filter actions are protected and should never be allowed to have a high priority
677     * intent filter for them. However, there is one, and only one exception -- the
678     * setup wizard. It must be able to define a high priority intent filter for these
679     * actions to ensure there are no escapes from the wizard. We need to delay processing
680     * of these during boot as we need to look at all of the system packages in order
681     * to know which component is the setup wizard.
682     */
683    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
684    /**
685     * Whether or not processing protected filters should be deferred.
686     */
687    private boolean mDeferProtectedFilters = true;
688
689    /**
690     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
691     */
692    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
693    /**
694     * Whether or not system app permissions should be promoted from install to runtime.
695     */
696    boolean mPromoteSystemApps;
697
698    @GuardedBy("mPackages")
699    final Settings mSettings;
700
701    /**
702     * Set of package names that are currently "frozen", which means active
703     * surgery is being done on the code/data for that package. The platform
704     * will refuse to launch frozen packages to avoid race conditions.
705     *
706     * @see PackageFreezer
707     */
708    @GuardedBy("mPackages")
709    final ArraySet<String> mFrozenPackages = new ArraySet<>();
710
711    final ProtectedPackages mProtectedPackages;
712
713    boolean mFirstBoot;
714
715    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
716
717    // System configuration read by SystemConfig.
718    final int[] mGlobalGids;
719    final SparseArray<ArraySet<String>> mSystemPermissions;
720    @GuardedBy("mAvailableFeatures")
721    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
722
723    // If mac_permissions.xml was found for seinfo labeling.
724    boolean mFoundPolicyFile;
725
726    private final InstantAppRegistry mInstantAppRegistry;
727
728    @GuardedBy("mPackages")
729    int mChangedPackagesSequenceNumber;
730    /**
731     * List of changed [installed, removed or updated] packages.
732     * mapping from user id -> sequence number -> package name
733     */
734    @GuardedBy("mPackages")
735    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
736    /**
737     * The sequence number of the last change to a package.
738     * mapping from user id -> package name -> sequence number
739     */
740    @GuardedBy("mPackages")
741    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
742
743    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
744        @Override public boolean hasFeature(String feature) {
745            return PackageManagerService.this.hasSystemFeature(feature, 0);
746        }
747    };
748
749    public static final class SharedLibraryEntry {
750        public final String path;
751        public final String apk;
752        public final SharedLibraryInfo info;
753
754        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
755                String declaringPackageName, int declaringPackageVersionCode) {
756            path = _path;
757            apk = _apk;
758            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
759                    declaringPackageName, declaringPackageVersionCode), null);
760        }
761    }
762
763    // Currently known shared libraries.
764    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
765    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
766            new ArrayMap<>();
767
768    // All available activities, for your resolving pleasure.
769    final ActivityIntentResolver mActivities =
770            new ActivityIntentResolver();
771
772    // All available receivers, for your resolving pleasure.
773    final ActivityIntentResolver mReceivers =
774            new ActivityIntentResolver();
775
776    // All available services, for your resolving pleasure.
777    final ServiceIntentResolver mServices = new ServiceIntentResolver();
778
779    // All available providers, for your resolving pleasure.
780    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
781
782    // Mapping from provider base names (first directory in content URI codePath)
783    // to the provider information.
784    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
785            new ArrayMap<String, PackageParser.Provider>();
786
787    // Mapping from instrumentation class names to info about them.
788    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
789            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
790
791    // Mapping from permission names to info about them.
792    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
793            new ArrayMap<String, PackageParser.PermissionGroup>();
794
795    // Packages whose data we have transfered into another package, thus
796    // should no longer exist.
797    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
798
799    // Broadcast actions that are only available to the system.
800    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
801
802    /** List of packages waiting for verification. */
803    final SparseArray<PackageVerificationState> mPendingVerification
804            = new SparseArray<PackageVerificationState>();
805
806    /** Set of packages associated with each app op permission. */
807    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
808
809    final PackageInstallerService mInstallerService;
810
811    private final PackageDexOptimizer mPackageDexOptimizer;
812    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
813    // is used by other apps).
814    private final DexManager mDexManager;
815
816    private AtomicInteger mNextMoveId = new AtomicInteger();
817    private final MoveCallbacks mMoveCallbacks;
818
819    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
820
821    // Cache of users who need badging.
822    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
823
824    /** Token for keys in mPendingVerification. */
825    private int mPendingVerificationToken = 0;
826
827    volatile boolean mSystemReady;
828    volatile boolean mSafeMode;
829    volatile boolean mHasSystemUidErrors;
830    private volatile boolean mEphemeralAppsDisabled;
831
832    ApplicationInfo mAndroidApplication;
833    final ActivityInfo mResolveActivity = new ActivityInfo();
834    final ResolveInfo mResolveInfo = new ResolveInfo();
835    ComponentName mResolveComponentName;
836    PackageParser.Package mPlatformPackage;
837    ComponentName mCustomResolverComponentName;
838
839    boolean mResolverReplaced = false;
840
841    private final @Nullable ComponentName mIntentFilterVerifierComponent;
842    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
843
844    private int mIntentFilterVerificationToken = 0;
845
846    /** The service connection to the ephemeral resolver */
847    final EphemeralResolverConnection mInstantAppResolverConnection;
848    /** Component used to show resolver settings for Instant Apps */
849    final ComponentName mInstantAppResolverSettingsComponent;
850
851    /** Activity used to install instant applications */
852    ActivityInfo mInstantAppInstallerActivity;
853    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
854
855    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
856            = new SparseArray<IntentFilterVerificationState>();
857
858    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
859
860    // List of packages names to keep cached, even if they are uninstalled for all users
861    private List<String> mKeepUninstalledPackages;
862
863    private UserManagerInternal mUserManagerInternal;
864
865    private DeviceIdleController.LocalService mDeviceIdleController;
866
867    private File mCacheDir;
868
869    private ArraySet<String> mPrivappPermissionsViolations;
870
871    private Future<?> mPrepareAppDataFuture;
872
873    private static class IFVerificationParams {
874        PackageParser.Package pkg;
875        boolean replacing;
876        int userId;
877        int verifierUid;
878
879        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
880                int _userId, int _verifierUid) {
881            pkg = _pkg;
882            replacing = _replacing;
883            userId = _userId;
884            replacing = _replacing;
885            verifierUid = _verifierUid;
886        }
887    }
888
889    private interface IntentFilterVerifier<T extends IntentFilter> {
890        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
891                                               T filter, String packageName);
892        void startVerifications(int userId);
893        void receiveVerificationResponse(int verificationId);
894    }
895
896    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
897        private Context mContext;
898        private ComponentName mIntentFilterVerifierComponent;
899        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
900
901        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
902            mContext = context;
903            mIntentFilterVerifierComponent = verifierComponent;
904        }
905
906        private String getDefaultScheme() {
907            return IntentFilter.SCHEME_HTTPS;
908        }
909
910        @Override
911        public void startVerifications(int userId) {
912            // Launch verifications requests
913            int count = mCurrentIntentFilterVerifications.size();
914            for (int n=0; n<count; n++) {
915                int verificationId = mCurrentIntentFilterVerifications.get(n);
916                final IntentFilterVerificationState ivs =
917                        mIntentFilterVerificationStates.get(verificationId);
918
919                String packageName = ivs.getPackageName();
920
921                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
922                final int filterCount = filters.size();
923                ArraySet<String> domainsSet = new ArraySet<>();
924                for (int m=0; m<filterCount; m++) {
925                    PackageParser.ActivityIntentInfo filter = filters.get(m);
926                    domainsSet.addAll(filter.getHostsList());
927                }
928                synchronized (mPackages) {
929                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
930                            packageName, domainsSet) != null) {
931                        scheduleWriteSettingsLocked();
932                    }
933                }
934                sendVerificationRequest(userId, verificationId, ivs);
935            }
936            mCurrentIntentFilterVerifications.clear();
937        }
938
939        private void sendVerificationRequest(int userId, int verificationId,
940                IntentFilterVerificationState ivs) {
941
942            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
943            verificationIntent.putExtra(
944                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
945                    verificationId);
946            verificationIntent.putExtra(
947                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
948                    getDefaultScheme());
949            verificationIntent.putExtra(
950                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
951                    ivs.getHostsString());
952            verificationIntent.putExtra(
953                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
954                    ivs.getPackageName());
955            verificationIntent.setComponent(mIntentFilterVerifierComponent);
956            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
957
958            DeviceIdleController.LocalService idleController = getDeviceIdleController();
959            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
960                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
961                    userId, false, "intent filter verifier");
962
963            UserHandle user = new UserHandle(userId);
964            mContext.sendBroadcastAsUser(verificationIntent, user);
965            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
966                    "Sending IntentFilter verification broadcast");
967        }
968
969        public void receiveVerificationResponse(int verificationId) {
970            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
971
972            final boolean verified = ivs.isVerified();
973
974            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
975            final int count = filters.size();
976            if (DEBUG_DOMAIN_VERIFICATION) {
977                Slog.i(TAG, "Received verification response " + verificationId
978                        + " for " + count + " filters, verified=" + verified);
979            }
980            for (int n=0; n<count; n++) {
981                PackageParser.ActivityIntentInfo filter = filters.get(n);
982                filter.setVerified(verified);
983
984                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
985                        + " verified with result:" + verified + " and hosts:"
986                        + ivs.getHostsString());
987            }
988
989            mIntentFilterVerificationStates.remove(verificationId);
990
991            final String packageName = ivs.getPackageName();
992            IntentFilterVerificationInfo ivi = null;
993
994            synchronized (mPackages) {
995                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
996            }
997            if (ivi == null) {
998                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
999                        + verificationId + " packageName:" + packageName);
1000                return;
1001            }
1002            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1003                    "Updating IntentFilterVerificationInfo for package " + packageName
1004                            +" verificationId:" + verificationId);
1005
1006            synchronized (mPackages) {
1007                if (verified) {
1008                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1009                } else {
1010                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1011                }
1012                scheduleWriteSettingsLocked();
1013
1014                final int userId = ivs.getUserId();
1015                if (userId != UserHandle.USER_ALL) {
1016                    final int userStatus =
1017                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1018
1019                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1020                    boolean needUpdate = false;
1021
1022                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1023                    // already been set by the User thru the Disambiguation dialog
1024                    switch (userStatus) {
1025                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1026                            if (verified) {
1027                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1028                            } else {
1029                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1030                            }
1031                            needUpdate = true;
1032                            break;
1033
1034                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1035                            if (verified) {
1036                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1037                                needUpdate = true;
1038                            }
1039                            break;
1040
1041                        default:
1042                            // Nothing to do
1043                    }
1044
1045                    if (needUpdate) {
1046                        mSettings.updateIntentFilterVerificationStatusLPw(
1047                                packageName, updatedStatus, userId);
1048                        scheduleWritePackageRestrictionsLocked(userId);
1049                    }
1050                }
1051            }
1052        }
1053
1054        @Override
1055        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1056                    ActivityIntentInfo filter, String packageName) {
1057            if (!hasValidDomains(filter)) {
1058                return false;
1059            }
1060            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1061            if (ivs == null) {
1062                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1063                        packageName);
1064            }
1065            if (DEBUG_DOMAIN_VERIFICATION) {
1066                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1067            }
1068            ivs.addFilter(filter);
1069            return true;
1070        }
1071
1072        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1073                int userId, int verificationId, String packageName) {
1074            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1075                    verifierUid, userId, packageName);
1076            ivs.setPendingState();
1077            synchronized (mPackages) {
1078                mIntentFilterVerificationStates.append(verificationId, ivs);
1079                mCurrentIntentFilterVerifications.add(verificationId);
1080            }
1081            return ivs;
1082        }
1083    }
1084
1085    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1086        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1087                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1088                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1089    }
1090
1091    // Set of pending broadcasts for aggregating enable/disable of components.
1092    static class PendingPackageBroadcasts {
1093        // for each user id, a map of <package name -> components within that package>
1094        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1095
1096        public PendingPackageBroadcasts() {
1097            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1098        }
1099
1100        public ArrayList<String> get(int userId, String packageName) {
1101            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1102            return packages.get(packageName);
1103        }
1104
1105        public void put(int userId, String packageName, ArrayList<String> components) {
1106            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1107            packages.put(packageName, components);
1108        }
1109
1110        public void remove(int userId, String packageName) {
1111            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1112            if (packages != null) {
1113                packages.remove(packageName);
1114            }
1115        }
1116
1117        public void remove(int userId) {
1118            mUidMap.remove(userId);
1119        }
1120
1121        public int userIdCount() {
1122            return mUidMap.size();
1123        }
1124
1125        public int userIdAt(int n) {
1126            return mUidMap.keyAt(n);
1127        }
1128
1129        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1130            return mUidMap.get(userId);
1131        }
1132
1133        public int size() {
1134            // total number of pending broadcast entries across all userIds
1135            int num = 0;
1136            for (int i = 0; i< mUidMap.size(); i++) {
1137                num += mUidMap.valueAt(i).size();
1138            }
1139            return num;
1140        }
1141
1142        public void clear() {
1143            mUidMap.clear();
1144        }
1145
1146        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1147            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1148            if (map == null) {
1149                map = new ArrayMap<String, ArrayList<String>>();
1150                mUidMap.put(userId, map);
1151            }
1152            return map;
1153        }
1154    }
1155    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1156
1157    // Service Connection to remote media container service to copy
1158    // package uri's from external media onto secure containers
1159    // or internal storage.
1160    private IMediaContainerService mContainerService = null;
1161
1162    static final int SEND_PENDING_BROADCAST = 1;
1163    static final int MCS_BOUND = 3;
1164    static final int END_COPY = 4;
1165    static final int INIT_COPY = 5;
1166    static final int MCS_UNBIND = 6;
1167    static final int START_CLEANING_PACKAGE = 7;
1168    static final int FIND_INSTALL_LOC = 8;
1169    static final int POST_INSTALL = 9;
1170    static final int MCS_RECONNECT = 10;
1171    static final int MCS_GIVE_UP = 11;
1172    static final int UPDATED_MEDIA_STATUS = 12;
1173    static final int WRITE_SETTINGS = 13;
1174    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1175    static final int PACKAGE_VERIFIED = 15;
1176    static final int CHECK_PENDING_VERIFICATION = 16;
1177    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1178    static final int INTENT_FILTER_VERIFIED = 18;
1179    static final int WRITE_PACKAGE_LIST = 19;
1180    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1181
1182    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1183
1184    // Delay time in millisecs
1185    static final int BROADCAST_DELAY = 10 * 1000;
1186
1187    static UserManagerService sUserManager;
1188
1189    // Stores a list of users whose package restrictions file needs to be updated
1190    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1191
1192    final private DefaultContainerConnection mDefContainerConn =
1193            new DefaultContainerConnection();
1194    class DefaultContainerConnection implements ServiceConnection {
1195        public void onServiceConnected(ComponentName name, IBinder service) {
1196            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1197            final IMediaContainerService imcs = IMediaContainerService.Stub
1198                    .asInterface(Binder.allowBlocking(service));
1199            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1200        }
1201
1202        public void onServiceDisconnected(ComponentName name) {
1203            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1204        }
1205    }
1206
1207    // Recordkeeping of restore-after-install operations that are currently in flight
1208    // between the Package Manager and the Backup Manager
1209    static class PostInstallData {
1210        public InstallArgs args;
1211        public PackageInstalledInfo res;
1212
1213        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1214            args = _a;
1215            res = _r;
1216        }
1217    }
1218
1219    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1220    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1221
1222    // XML tags for backup/restore of various bits of state
1223    private static final String TAG_PREFERRED_BACKUP = "pa";
1224    private static final String TAG_DEFAULT_APPS = "da";
1225    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1226
1227    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1228    private static final String TAG_ALL_GRANTS = "rt-grants";
1229    private static final String TAG_GRANT = "grant";
1230    private static final String ATTR_PACKAGE_NAME = "pkg";
1231
1232    private static final String TAG_PERMISSION = "perm";
1233    private static final String ATTR_PERMISSION_NAME = "name";
1234    private static final String ATTR_IS_GRANTED = "g";
1235    private static final String ATTR_USER_SET = "set";
1236    private static final String ATTR_USER_FIXED = "fixed";
1237    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1238
1239    // System/policy permission grants are not backed up
1240    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1241            FLAG_PERMISSION_POLICY_FIXED
1242            | FLAG_PERMISSION_SYSTEM_FIXED
1243            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1244
1245    // And we back up these user-adjusted states
1246    private static final int USER_RUNTIME_GRANT_MASK =
1247            FLAG_PERMISSION_USER_SET
1248            | FLAG_PERMISSION_USER_FIXED
1249            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1250
1251    final @Nullable String mRequiredVerifierPackage;
1252    final @NonNull String mRequiredInstallerPackage;
1253    final @NonNull String mRequiredUninstallerPackage;
1254    final @Nullable String mSetupWizardPackage;
1255    final @Nullable String mStorageManagerPackage;
1256    final @NonNull String mServicesSystemSharedLibraryPackageName;
1257    final @NonNull String mSharedSystemSharedLibraryPackageName;
1258
1259    final boolean mPermissionReviewRequired;
1260
1261    private final PackageUsage mPackageUsage = new PackageUsage();
1262    private final CompilerStats mCompilerStats = new CompilerStats();
1263
1264    class PackageHandler extends Handler {
1265        private boolean mBound = false;
1266        final ArrayList<HandlerParams> mPendingInstalls =
1267            new ArrayList<HandlerParams>();
1268
1269        private boolean connectToService() {
1270            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1271                    " DefaultContainerService");
1272            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1273            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1274            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1275                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1276                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1277                mBound = true;
1278                return true;
1279            }
1280            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1281            return false;
1282        }
1283
1284        private void disconnectService() {
1285            mContainerService = null;
1286            mBound = false;
1287            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1288            mContext.unbindService(mDefContainerConn);
1289            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1290        }
1291
1292        PackageHandler(Looper looper) {
1293            super(looper);
1294        }
1295
1296        public void handleMessage(Message msg) {
1297            try {
1298                doHandleMessage(msg);
1299            } finally {
1300                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1301            }
1302        }
1303
1304        void doHandleMessage(Message msg) {
1305            switch (msg.what) {
1306                case INIT_COPY: {
1307                    HandlerParams params = (HandlerParams) msg.obj;
1308                    int idx = mPendingInstalls.size();
1309                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1310                    // If a bind was already initiated we dont really
1311                    // need to do anything. The pending install
1312                    // will be processed later on.
1313                    if (!mBound) {
1314                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1315                                System.identityHashCode(mHandler));
1316                        // If this is the only one pending we might
1317                        // have to bind to the service again.
1318                        if (!connectToService()) {
1319                            Slog.e(TAG, "Failed to bind to media container service");
1320                            params.serviceError();
1321                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1322                                    System.identityHashCode(mHandler));
1323                            if (params.traceMethod != null) {
1324                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1325                                        params.traceCookie);
1326                            }
1327                            return;
1328                        } else {
1329                            // Once we bind to the service, the first
1330                            // pending request will be processed.
1331                            mPendingInstalls.add(idx, params);
1332                        }
1333                    } else {
1334                        mPendingInstalls.add(idx, params);
1335                        // Already bound to the service. Just make
1336                        // sure we trigger off processing the first request.
1337                        if (idx == 0) {
1338                            mHandler.sendEmptyMessage(MCS_BOUND);
1339                        }
1340                    }
1341                    break;
1342                }
1343                case MCS_BOUND: {
1344                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1345                    if (msg.obj != null) {
1346                        mContainerService = (IMediaContainerService) msg.obj;
1347                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1348                                System.identityHashCode(mHandler));
1349                    }
1350                    if (mContainerService == null) {
1351                        if (!mBound) {
1352                            // Something seriously wrong since we are not bound and we are not
1353                            // waiting for connection. Bail out.
1354                            Slog.e(TAG, "Cannot bind to media container service");
1355                            for (HandlerParams params : mPendingInstalls) {
1356                                // Indicate service bind error
1357                                params.serviceError();
1358                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1359                                        System.identityHashCode(params));
1360                                if (params.traceMethod != null) {
1361                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1362                                            params.traceMethod, params.traceCookie);
1363                                }
1364                                return;
1365                            }
1366                            mPendingInstalls.clear();
1367                        } else {
1368                            Slog.w(TAG, "Waiting to connect to media container service");
1369                        }
1370                    } else if (mPendingInstalls.size() > 0) {
1371                        HandlerParams params = mPendingInstalls.get(0);
1372                        if (params != null) {
1373                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1374                                    System.identityHashCode(params));
1375                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1376                            if (params.startCopy()) {
1377                                // We are done...  look for more work or to
1378                                // go idle.
1379                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1380                                        "Checking for more work or unbind...");
1381                                // Delete pending install
1382                                if (mPendingInstalls.size() > 0) {
1383                                    mPendingInstalls.remove(0);
1384                                }
1385                                if (mPendingInstalls.size() == 0) {
1386                                    if (mBound) {
1387                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1388                                                "Posting delayed MCS_UNBIND");
1389                                        removeMessages(MCS_UNBIND);
1390                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1391                                        // Unbind after a little delay, to avoid
1392                                        // continual thrashing.
1393                                        sendMessageDelayed(ubmsg, 10000);
1394                                    }
1395                                } else {
1396                                    // There are more pending requests in queue.
1397                                    // Just post MCS_BOUND message to trigger processing
1398                                    // of next pending install.
1399                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1400                                            "Posting MCS_BOUND for next work");
1401                                    mHandler.sendEmptyMessage(MCS_BOUND);
1402                                }
1403                            }
1404                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1405                        }
1406                    } else {
1407                        // Should never happen ideally.
1408                        Slog.w(TAG, "Empty queue");
1409                    }
1410                    break;
1411                }
1412                case MCS_RECONNECT: {
1413                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1414                    if (mPendingInstalls.size() > 0) {
1415                        if (mBound) {
1416                            disconnectService();
1417                        }
1418                        if (!connectToService()) {
1419                            Slog.e(TAG, "Failed to bind to media container service");
1420                            for (HandlerParams params : mPendingInstalls) {
1421                                // Indicate service bind error
1422                                params.serviceError();
1423                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1424                                        System.identityHashCode(params));
1425                            }
1426                            mPendingInstalls.clear();
1427                        }
1428                    }
1429                    break;
1430                }
1431                case MCS_UNBIND: {
1432                    // If there is no actual work left, then time to unbind.
1433                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1434
1435                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1436                        if (mBound) {
1437                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1438
1439                            disconnectService();
1440                        }
1441                    } else if (mPendingInstalls.size() > 0) {
1442                        // There are more pending requests in queue.
1443                        // Just post MCS_BOUND message to trigger processing
1444                        // of next pending install.
1445                        mHandler.sendEmptyMessage(MCS_BOUND);
1446                    }
1447
1448                    break;
1449                }
1450                case MCS_GIVE_UP: {
1451                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1452                    HandlerParams params = mPendingInstalls.remove(0);
1453                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1454                            System.identityHashCode(params));
1455                    break;
1456                }
1457                case SEND_PENDING_BROADCAST: {
1458                    String packages[];
1459                    ArrayList<String> components[];
1460                    int size = 0;
1461                    int uids[];
1462                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1463                    synchronized (mPackages) {
1464                        if (mPendingBroadcasts == null) {
1465                            return;
1466                        }
1467                        size = mPendingBroadcasts.size();
1468                        if (size <= 0) {
1469                            // Nothing to be done. Just return
1470                            return;
1471                        }
1472                        packages = new String[size];
1473                        components = new ArrayList[size];
1474                        uids = new int[size];
1475                        int i = 0;  // filling out the above arrays
1476
1477                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1478                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1479                            Iterator<Map.Entry<String, ArrayList<String>>> it
1480                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1481                                            .entrySet().iterator();
1482                            while (it.hasNext() && i < size) {
1483                                Map.Entry<String, ArrayList<String>> ent = it.next();
1484                                packages[i] = ent.getKey();
1485                                components[i] = ent.getValue();
1486                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1487                                uids[i] = (ps != null)
1488                                        ? UserHandle.getUid(packageUserId, ps.appId)
1489                                        : -1;
1490                                i++;
1491                            }
1492                        }
1493                        size = i;
1494                        mPendingBroadcasts.clear();
1495                    }
1496                    // Send broadcasts
1497                    for (int i = 0; i < size; i++) {
1498                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1499                    }
1500                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1501                    break;
1502                }
1503                case START_CLEANING_PACKAGE: {
1504                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1505                    final String packageName = (String)msg.obj;
1506                    final int userId = msg.arg1;
1507                    final boolean andCode = msg.arg2 != 0;
1508                    synchronized (mPackages) {
1509                        if (userId == UserHandle.USER_ALL) {
1510                            int[] users = sUserManager.getUserIds();
1511                            for (int user : users) {
1512                                mSettings.addPackageToCleanLPw(
1513                                        new PackageCleanItem(user, packageName, andCode));
1514                            }
1515                        } else {
1516                            mSettings.addPackageToCleanLPw(
1517                                    new PackageCleanItem(userId, packageName, andCode));
1518                        }
1519                    }
1520                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1521                    startCleaningPackages();
1522                } break;
1523                case POST_INSTALL: {
1524                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1525
1526                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1527                    final boolean didRestore = (msg.arg2 != 0);
1528                    mRunningInstalls.delete(msg.arg1);
1529
1530                    if (data != null) {
1531                        InstallArgs args = data.args;
1532                        PackageInstalledInfo parentRes = data.res;
1533
1534                        final boolean grantPermissions = (args.installFlags
1535                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1536                        final boolean killApp = (args.installFlags
1537                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1538                        final String[] grantedPermissions = args.installGrantPermissions;
1539
1540                        // Handle the parent package
1541                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1542                                grantedPermissions, didRestore, args.installerPackageName,
1543                                args.observer);
1544
1545                        // Handle the child packages
1546                        final int childCount = (parentRes.addedChildPackages != null)
1547                                ? parentRes.addedChildPackages.size() : 0;
1548                        for (int i = 0; i < childCount; i++) {
1549                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1550                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1551                                    grantedPermissions, false, args.installerPackageName,
1552                                    args.observer);
1553                        }
1554
1555                        // Log tracing if needed
1556                        if (args.traceMethod != null) {
1557                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1558                                    args.traceCookie);
1559                        }
1560                    } else {
1561                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1562                    }
1563
1564                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1565                } break;
1566                case UPDATED_MEDIA_STATUS: {
1567                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1568                    boolean reportStatus = msg.arg1 == 1;
1569                    boolean doGc = msg.arg2 == 1;
1570                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1571                    if (doGc) {
1572                        // Force a gc to clear up stale containers.
1573                        Runtime.getRuntime().gc();
1574                    }
1575                    if (msg.obj != null) {
1576                        @SuppressWarnings("unchecked")
1577                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1578                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1579                        // Unload containers
1580                        unloadAllContainers(args);
1581                    }
1582                    if (reportStatus) {
1583                        try {
1584                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1585                                    "Invoking StorageManagerService call back");
1586                            PackageHelper.getStorageManager().finishMediaUpdate();
1587                        } catch (RemoteException e) {
1588                            Log.e(TAG, "StorageManagerService not running?");
1589                        }
1590                    }
1591                } break;
1592                case WRITE_SETTINGS: {
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1594                    synchronized (mPackages) {
1595                        removeMessages(WRITE_SETTINGS);
1596                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1597                        mSettings.writeLPr();
1598                        mDirtyUsers.clear();
1599                    }
1600                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1601                } break;
1602                case WRITE_PACKAGE_RESTRICTIONS: {
1603                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1604                    synchronized (mPackages) {
1605                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1606                        for (int userId : mDirtyUsers) {
1607                            mSettings.writePackageRestrictionsLPr(userId);
1608                        }
1609                        mDirtyUsers.clear();
1610                    }
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1612                } break;
1613                case WRITE_PACKAGE_LIST: {
1614                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1615                    synchronized (mPackages) {
1616                        removeMessages(WRITE_PACKAGE_LIST);
1617                        mSettings.writePackageListLPr(msg.arg1);
1618                    }
1619                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1620                } break;
1621                case CHECK_PENDING_VERIFICATION: {
1622                    final int verificationId = msg.arg1;
1623                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1624
1625                    if ((state != null) && !state.timeoutExtended()) {
1626                        final InstallArgs args = state.getInstallArgs();
1627                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1628
1629                        Slog.i(TAG, "Verification timed out for " + originUri);
1630                        mPendingVerification.remove(verificationId);
1631
1632                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1633
1634                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1635                            Slog.i(TAG, "Continuing with installation of " + originUri);
1636                            state.setVerifierResponse(Binder.getCallingUid(),
1637                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1638                            broadcastPackageVerified(verificationId, originUri,
1639                                    PackageManager.VERIFICATION_ALLOW,
1640                                    state.getInstallArgs().getUser());
1641                            try {
1642                                ret = args.copyApk(mContainerService, true);
1643                            } catch (RemoteException e) {
1644                                Slog.e(TAG, "Could not contact the ContainerService");
1645                            }
1646                        } else {
1647                            broadcastPackageVerified(verificationId, originUri,
1648                                    PackageManager.VERIFICATION_REJECT,
1649                                    state.getInstallArgs().getUser());
1650                        }
1651
1652                        Trace.asyncTraceEnd(
1653                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1654
1655                        processPendingInstall(args, ret);
1656                        mHandler.sendEmptyMessage(MCS_UNBIND);
1657                    }
1658                    break;
1659                }
1660                case PACKAGE_VERIFIED: {
1661                    final int verificationId = msg.arg1;
1662
1663                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1664                    if (state == null) {
1665                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1666                        break;
1667                    }
1668
1669                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1670
1671                    state.setVerifierResponse(response.callerUid, response.code);
1672
1673                    if (state.isVerificationComplete()) {
1674                        mPendingVerification.remove(verificationId);
1675
1676                        final InstallArgs args = state.getInstallArgs();
1677                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1678
1679                        int ret;
1680                        if (state.isInstallAllowed()) {
1681                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1682                            broadcastPackageVerified(verificationId, originUri,
1683                                    response.code, state.getInstallArgs().getUser());
1684                            try {
1685                                ret = args.copyApk(mContainerService, true);
1686                            } catch (RemoteException e) {
1687                                Slog.e(TAG, "Could not contact the ContainerService");
1688                            }
1689                        } else {
1690                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1691                        }
1692
1693                        Trace.asyncTraceEnd(
1694                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1695
1696                        processPendingInstall(args, ret);
1697                        mHandler.sendEmptyMessage(MCS_UNBIND);
1698                    }
1699
1700                    break;
1701                }
1702                case START_INTENT_FILTER_VERIFICATIONS: {
1703                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1704                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1705                            params.replacing, params.pkg);
1706                    break;
1707                }
1708                case INTENT_FILTER_VERIFIED: {
1709                    final int verificationId = msg.arg1;
1710
1711                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1712                            verificationId);
1713                    if (state == null) {
1714                        Slog.w(TAG, "Invalid IntentFilter verification token "
1715                                + verificationId + " received");
1716                        break;
1717                    }
1718
1719                    final int userId = state.getUserId();
1720
1721                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1722                            "Processing IntentFilter verification with token:"
1723                            + verificationId + " and userId:" + userId);
1724
1725                    final IntentFilterVerificationResponse response =
1726                            (IntentFilterVerificationResponse) msg.obj;
1727
1728                    state.setVerifierResponse(response.callerUid, response.code);
1729
1730                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1731                            "IntentFilter verification with token:" + verificationId
1732                            + " and userId:" + userId
1733                            + " is settings verifier response with response code:"
1734                            + response.code);
1735
1736                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1737                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1738                                + response.getFailedDomainsString());
1739                    }
1740
1741                    if (state.isVerificationComplete()) {
1742                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1743                    } else {
1744                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1745                                "IntentFilter verification with token:" + verificationId
1746                                + " was not said to be complete");
1747                    }
1748
1749                    break;
1750                }
1751                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1752                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1753                            mInstantAppResolverConnection,
1754                            (InstantAppRequest) msg.obj,
1755                            mInstantAppInstallerActivity,
1756                            mHandler);
1757                }
1758            }
1759        }
1760    }
1761
1762    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1763            boolean killApp, String[] grantedPermissions,
1764            boolean launchedForRestore, String installerPackage,
1765            IPackageInstallObserver2 installObserver) {
1766        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1767            // Send the removed broadcasts
1768            if (res.removedInfo != null) {
1769                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1770            }
1771
1772            // Now that we successfully installed the package, grant runtime
1773            // permissions if requested before broadcasting the install. Also
1774            // for legacy apps in permission review mode we clear the permission
1775            // review flag which is used to emulate runtime permissions for
1776            // legacy apps.
1777            if (grantPermissions) {
1778                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1779            }
1780
1781            final boolean update = res.removedInfo != null
1782                    && res.removedInfo.removedPackage != null;
1783
1784            // If this is the first time we have child packages for a disabled privileged
1785            // app that had no children, we grant requested runtime permissions to the new
1786            // children if the parent on the system image had them already granted.
1787            if (res.pkg.parentPackage != null) {
1788                synchronized (mPackages) {
1789                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1790                }
1791            }
1792
1793            synchronized (mPackages) {
1794                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1795            }
1796
1797            final String packageName = res.pkg.applicationInfo.packageName;
1798
1799            // Determine the set of users who are adding this package for
1800            // the first time vs. those who are seeing an update.
1801            int[] firstUsers = EMPTY_INT_ARRAY;
1802            int[] updateUsers = EMPTY_INT_ARRAY;
1803            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1804            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1805            for (int newUser : res.newUsers) {
1806                if (ps.getInstantApp(newUser)) {
1807                    continue;
1808                }
1809                if (allNewUsers) {
1810                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1811                    continue;
1812                }
1813                boolean isNew = true;
1814                for (int origUser : res.origUsers) {
1815                    if (origUser == newUser) {
1816                        isNew = false;
1817                        break;
1818                    }
1819                }
1820                if (isNew) {
1821                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1822                } else {
1823                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1824                }
1825            }
1826
1827            // Send installed broadcasts if the package is not a static shared lib.
1828            if (res.pkg.staticSharedLibName == null) {
1829                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1830
1831                // Send added for users that see the package for the first time
1832                // sendPackageAddedForNewUsers also deals with system apps
1833                int appId = UserHandle.getAppId(res.uid);
1834                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1835                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1836
1837                // Send added for users that don't see the package for the first time
1838                Bundle extras = new Bundle(1);
1839                extras.putInt(Intent.EXTRA_UID, res.uid);
1840                if (update) {
1841                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1842                }
1843                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1844                        extras, 0 /*flags*/, null /*targetPackage*/,
1845                        null /*finishedReceiver*/, updateUsers);
1846
1847                // Send replaced for users that don't see the package for the first time
1848                if (update) {
1849                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1850                            packageName, extras, 0 /*flags*/,
1851                            null /*targetPackage*/, null /*finishedReceiver*/,
1852                            updateUsers);
1853                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1854                            null /*package*/, null /*extras*/, 0 /*flags*/,
1855                            packageName /*targetPackage*/,
1856                            null /*finishedReceiver*/, updateUsers);
1857                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1858                    // First-install and we did a restore, so we're responsible for the
1859                    // first-launch broadcast.
1860                    if (DEBUG_BACKUP) {
1861                        Slog.i(TAG, "Post-restore of " + packageName
1862                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1863                    }
1864                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1865                }
1866
1867                // Send broadcast package appeared if forward locked/external for all users
1868                // treat asec-hosted packages like removable media on upgrade
1869                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1870                    if (DEBUG_INSTALL) {
1871                        Slog.i(TAG, "upgrading pkg " + res.pkg
1872                                + " is ASEC-hosted -> AVAILABLE");
1873                    }
1874                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1875                    ArrayList<String> pkgList = new ArrayList<>(1);
1876                    pkgList.add(packageName);
1877                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1878                }
1879            }
1880
1881            // Work that needs to happen on first install within each user
1882            if (firstUsers != null && firstUsers.length > 0) {
1883                synchronized (mPackages) {
1884                    for (int userId : firstUsers) {
1885                        // If this app is a browser and it's newly-installed for some
1886                        // users, clear any default-browser state in those users. The
1887                        // app's nature doesn't depend on the user, so we can just check
1888                        // its browser nature in any user and generalize.
1889                        if (packageIsBrowser(packageName, userId)) {
1890                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1891                        }
1892
1893                        // We may also need to apply pending (restored) runtime
1894                        // permission grants within these users.
1895                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1896                    }
1897                }
1898            }
1899
1900            // Log current value of "unknown sources" setting
1901            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1902                    getUnknownSourcesSettings());
1903
1904            // Force a gc to clear up things
1905            Runtime.getRuntime().gc();
1906
1907            // Remove the replaced package's older resources safely now
1908            // We delete after a gc for applications  on sdcard.
1909            if (res.removedInfo != null && res.removedInfo.args != null) {
1910                synchronized (mInstallLock) {
1911                    res.removedInfo.args.doPostDeleteLI(true);
1912                }
1913            }
1914
1915            // Notify DexManager that the package was installed for new users.
1916            // The updated users should already be indexed and the package code paths
1917            // should not change.
1918            // Don't notify the manager for ephemeral apps as they are not expected to
1919            // survive long enough to benefit of background optimizations.
1920            for (int userId : firstUsers) {
1921                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1922                // There's a race currently where some install events may interleave with an uninstall.
1923                // This can lead to package info being null (b/36642664).
1924                if (info != null) {
1925                    mDexManager.notifyPackageInstalled(info, userId);
1926                }
1927            }
1928        }
1929
1930        // If someone is watching installs - notify them
1931        if (installObserver != null) {
1932            try {
1933                Bundle extras = extrasForInstallResult(res);
1934                installObserver.onPackageInstalled(res.name, res.returnCode,
1935                        res.returnMsg, extras);
1936            } catch (RemoteException e) {
1937                Slog.i(TAG, "Observer no longer exists.");
1938            }
1939        }
1940    }
1941
1942    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1943            PackageParser.Package pkg) {
1944        if (pkg.parentPackage == null) {
1945            return;
1946        }
1947        if (pkg.requestedPermissions == null) {
1948            return;
1949        }
1950        final PackageSetting disabledSysParentPs = mSettings
1951                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1952        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1953                || !disabledSysParentPs.isPrivileged()
1954                || (disabledSysParentPs.childPackageNames != null
1955                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1956            return;
1957        }
1958        final int[] allUserIds = sUserManager.getUserIds();
1959        final int permCount = pkg.requestedPermissions.size();
1960        for (int i = 0; i < permCount; i++) {
1961            String permission = pkg.requestedPermissions.get(i);
1962            BasePermission bp = mSettings.mPermissions.get(permission);
1963            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1964                continue;
1965            }
1966            for (int userId : allUserIds) {
1967                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1968                        permission, userId)) {
1969                    grantRuntimePermission(pkg.packageName, permission, userId);
1970                }
1971            }
1972        }
1973    }
1974
1975    private StorageEventListener mStorageListener = new StorageEventListener() {
1976        @Override
1977        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1978            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1979                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1980                    final String volumeUuid = vol.getFsUuid();
1981
1982                    // Clean up any users or apps that were removed or recreated
1983                    // while this volume was missing
1984                    sUserManager.reconcileUsers(volumeUuid);
1985                    reconcileApps(volumeUuid);
1986
1987                    // Clean up any install sessions that expired or were
1988                    // cancelled while this volume was missing
1989                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1990
1991                    loadPrivatePackages(vol);
1992
1993                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1994                    unloadPrivatePackages(vol);
1995                }
1996            }
1997
1998            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1999                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2000                    updateExternalMediaStatus(true, false);
2001                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2002                    updateExternalMediaStatus(false, false);
2003                }
2004            }
2005        }
2006
2007        @Override
2008        public void onVolumeForgotten(String fsUuid) {
2009            if (TextUtils.isEmpty(fsUuid)) {
2010                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2011                return;
2012            }
2013
2014            // Remove any apps installed on the forgotten volume
2015            synchronized (mPackages) {
2016                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2017                for (PackageSetting ps : packages) {
2018                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2019                    deletePackageVersioned(new VersionedPackage(ps.name,
2020                            PackageManager.VERSION_CODE_HIGHEST),
2021                            new LegacyPackageDeleteObserver(null).getBinder(),
2022                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2023                    // Try very hard to release any references to this package
2024                    // so we don't risk the system server being killed due to
2025                    // open FDs
2026                    AttributeCache.instance().removePackage(ps.name);
2027                }
2028
2029                mSettings.onVolumeForgotten(fsUuid);
2030                mSettings.writeLPr();
2031            }
2032        }
2033    };
2034
2035    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2036            String[] grantedPermissions) {
2037        for (int userId : userIds) {
2038            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2039        }
2040    }
2041
2042    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2043            String[] grantedPermissions) {
2044        SettingBase sb = (SettingBase) pkg.mExtras;
2045        if (sb == null) {
2046            return;
2047        }
2048
2049        PermissionsState permissionsState = sb.getPermissionsState();
2050
2051        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2052                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2053
2054        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2055                >= Build.VERSION_CODES.M;
2056
2057        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2058
2059        for (String permission : pkg.requestedPermissions) {
2060            final BasePermission bp;
2061            synchronized (mPackages) {
2062                bp = mSettings.mPermissions.get(permission);
2063            }
2064            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2065                    && (!instantApp || bp.isInstant())
2066                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2067                    && (grantedPermissions == null
2068                           || ArrayUtils.contains(grantedPermissions, permission))) {
2069                final int flags = permissionsState.getPermissionFlags(permission, userId);
2070                if (supportsRuntimePermissions) {
2071                    // Installer cannot change immutable permissions.
2072                    if ((flags & immutableFlags) == 0) {
2073                        grantRuntimePermission(pkg.packageName, permission, userId);
2074                    }
2075                } else if (mPermissionReviewRequired) {
2076                    // In permission review mode we clear the review flag when we
2077                    // are asked to install the app with all permissions granted.
2078                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2079                        updatePermissionFlags(permission, pkg.packageName,
2080                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2081                    }
2082                }
2083            }
2084        }
2085    }
2086
2087    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2088        Bundle extras = null;
2089        switch (res.returnCode) {
2090            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2091                extras = new Bundle();
2092                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2093                        res.origPermission);
2094                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2095                        res.origPackage);
2096                break;
2097            }
2098            case PackageManager.INSTALL_SUCCEEDED: {
2099                extras = new Bundle();
2100                extras.putBoolean(Intent.EXTRA_REPLACING,
2101                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2102                break;
2103            }
2104        }
2105        return extras;
2106    }
2107
2108    void scheduleWriteSettingsLocked() {
2109        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2110            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2111        }
2112    }
2113
2114    void scheduleWritePackageListLocked(int userId) {
2115        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2116            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2117            msg.arg1 = userId;
2118            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2119        }
2120    }
2121
2122    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2123        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2124        scheduleWritePackageRestrictionsLocked(userId);
2125    }
2126
2127    void scheduleWritePackageRestrictionsLocked(int userId) {
2128        final int[] userIds = (userId == UserHandle.USER_ALL)
2129                ? sUserManager.getUserIds() : new int[]{userId};
2130        for (int nextUserId : userIds) {
2131            if (!sUserManager.exists(nextUserId)) return;
2132            mDirtyUsers.add(nextUserId);
2133            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2134                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2135            }
2136        }
2137    }
2138
2139    public static PackageManagerService main(Context context, Installer installer,
2140            boolean factoryTest, boolean onlyCore) {
2141        // Self-check for initial settings.
2142        PackageManagerServiceCompilerMapping.checkProperties();
2143
2144        PackageManagerService m = new PackageManagerService(context, installer,
2145                factoryTest, onlyCore);
2146        m.enableSystemUserPackages();
2147        ServiceManager.addService("package", m);
2148        return m;
2149    }
2150
2151    private void enableSystemUserPackages() {
2152        if (!UserManager.isSplitSystemUser()) {
2153            return;
2154        }
2155        // For system user, enable apps based on the following conditions:
2156        // - app is whitelisted or belong to one of these groups:
2157        //   -- system app which has no launcher icons
2158        //   -- system app which has INTERACT_ACROSS_USERS permission
2159        //   -- system IME app
2160        // - app is not in the blacklist
2161        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2162        Set<String> enableApps = new ArraySet<>();
2163        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2164                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2165                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2166        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2167        enableApps.addAll(wlApps);
2168        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2169                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2170        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2171        enableApps.removeAll(blApps);
2172        Log.i(TAG, "Applications installed for system user: " + enableApps);
2173        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2174                UserHandle.SYSTEM);
2175        final int allAppsSize = allAps.size();
2176        synchronized (mPackages) {
2177            for (int i = 0; i < allAppsSize; i++) {
2178                String pName = allAps.get(i);
2179                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2180                // Should not happen, but we shouldn't be failing if it does
2181                if (pkgSetting == null) {
2182                    continue;
2183                }
2184                boolean install = enableApps.contains(pName);
2185                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2186                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2187                            + " for system user");
2188                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2189                }
2190            }
2191            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2192        }
2193    }
2194
2195    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2196        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2197                Context.DISPLAY_SERVICE);
2198        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2199    }
2200
2201    /**
2202     * Requests that files preopted on a secondary system partition be copied to the data partition
2203     * if possible.  Note that the actual copying of the files is accomplished by init for security
2204     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2205     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2206     */
2207    private static void requestCopyPreoptedFiles() {
2208        final int WAIT_TIME_MS = 100;
2209        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2210        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2211            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2212            // We will wait for up to 100 seconds.
2213            final long timeStart = SystemClock.uptimeMillis();
2214            final long timeEnd = timeStart + 100 * 1000;
2215            long timeNow = timeStart;
2216            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2217                try {
2218                    Thread.sleep(WAIT_TIME_MS);
2219                } catch (InterruptedException e) {
2220                    // Do nothing
2221                }
2222                timeNow = SystemClock.uptimeMillis();
2223                if (timeNow > timeEnd) {
2224                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2225                    Slog.wtf(TAG, "cppreopt did not finish!");
2226                    break;
2227                }
2228            }
2229
2230            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2231        }
2232    }
2233
2234    public PackageManagerService(Context context, Installer installer,
2235            boolean factoryTest, boolean onlyCore) {
2236        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2237        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2238        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2239                SystemClock.uptimeMillis());
2240
2241        if (mSdkVersion <= 0) {
2242            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2243        }
2244
2245        mContext = context;
2246
2247        mPermissionReviewRequired = context.getResources().getBoolean(
2248                R.bool.config_permissionReviewRequired);
2249
2250        mFactoryTest = factoryTest;
2251        mOnlyCore = onlyCore;
2252        mMetrics = new DisplayMetrics();
2253        mSettings = new Settings(mPackages);
2254        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2255                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2256        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2257                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2258        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2259                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2260        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2261                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2262        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2263                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2264        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2265                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2266
2267        String separateProcesses = SystemProperties.get("debug.separate_processes");
2268        if (separateProcesses != null && separateProcesses.length() > 0) {
2269            if ("*".equals(separateProcesses)) {
2270                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2271                mSeparateProcesses = null;
2272                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2273            } else {
2274                mDefParseFlags = 0;
2275                mSeparateProcesses = separateProcesses.split(",");
2276                Slog.w(TAG, "Running with debug.separate_processes: "
2277                        + separateProcesses);
2278            }
2279        } else {
2280            mDefParseFlags = 0;
2281            mSeparateProcesses = null;
2282        }
2283
2284        mInstaller = installer;
2285        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2286                "*dexopt*");
2287        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2288        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2289
2290        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2291                FgThread.get().getLooper());
2292
2293        getDefaultDisplayMetrics(context, mMetrics);
2294
2295        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2296        SystemConfig systemConfig = SystemConfig.getInstance();
2297        mGlobalGids = systemConfig.getGlobalGids();
2298        mSystemPermissions = systemConfig.getSystemPermissions();
2299        mAvailableFeatures = systemConfig.getAvailableFeatures();
2300        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2301
2302        mProtectedPackages = new ProtectedPackages(mContext);
2303
2304        synchronized (mInstallLock) {
2305        // writer
2306        synchronized (mPackages) {
2307            mHandlerThread = new ServiceThread(TAG,
2308                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2309            mHandlerThread.start();
2310            mHandler = new PackageHandler(mHandlerThread.getLooper());
2311            mProcessLoggingHandler = new ProcessLoggingHandler();
2312            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2313
2314            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2315            mInstantAppRegistry = new InstantAppRegistry(this);
2316
2317            File dataDir = Environment.getDataDirectory();
2318            mAppInstallDir = new File(dataDir, "app");
2319            mAppLib32InstallDir = new File(dataDir, "app-lib");
2320            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2321            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2322            sUserManager = new UserManagerService(context, this,
2323                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2324
2325            // Propagate permission configuration in to package manager.
2326            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2327                    = systemConfig.getPermissions();
2328            for (int i=0; i<permConfig.size(); i++) {
2329                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2330                BasePermission bp = mSettings.mPermissions.get(perm.name);
2331                if (bp == null) {
2332                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2333                    mSettings.mPermissions.put(perm.name, bp);
2334                }
2335                if (perm.gids != null) {
2336                    bp.setGids(perm.gids, perm.perUser);
2337                }
2338            }
2339
2340            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2341            final int builtInLibCount = libConfig.size();
2342            for (int i = 0; i < builtInLibCount; i++) {
2343                String name = libConfig.keyAt(i);
2344                String path = libConfig.valueAt(i);
2345                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2346                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2347            }
2348
2349            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2350
2351            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2352            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2353            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2354
2355            // Clean up orphaned packages for which the code path doesn't exist
2356            // and they are an update to a system app - caused by bug/32321269
2357            final int packageSettingCount = mSettings.mPackages.size();
2358            for (int i = packageSettingCount - 1; i >= 0; i--) {
2359                PackageSetting ps = mSettings.mPackages.valueAt(i);
2360                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2361                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2362                    mSettings.mPackages.removeAt(i);
2363                    mSettings.enableSystemPackageLPw(ps.name);
2364                }
2365            }
2366
2367            if (mFirstBoot) {
2368                requestCopyPreoptedFiles();
2369            }
2370
2371            String customResolverActivity = Resources.getSystem().getString(
2372                    R.string.config_customResolverActivity);
2373            if (TextUtils.isEmpty(customResolverActivity)) {
2374                customResolverActivity = null;
2375            } else {
2376                mCustomResolverComponentName = ComponentName.unflattenFromString(
2377                        customResolverActivity);
2378            }
2379
2380            long startTime = SystemClock.uptimeMillis();
2381
2382            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2383                    startTime);
2384
2385            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2386            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2387
2388            if (bootClassPath == null) {
2389                Slog.w(TAG, "No BOOTCLASSPATH found!");
2390            }
2391
2392            if (systemServerClassPath == null) {
2393                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2394            }
2395
2396            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2397
2398            final VersionInfo ver = mSettings.getInternalVersion();
2399            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2400            if (mIsUpgrade) {
2401                logCriticalInfo(Log.INFO,
2402                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2403            }
2404
2405            // when upgrading from pre-M, promote system app permissions from install to runtime
2406            mPromoteSystemApps =
2407                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2408
2409            // When upgrading from pre-N, we need to handle package extraction like first boot,
2410            // as there is no profiling data available.
2411            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2412
2413            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2414
2415            // save off the names of pre-existing system packages prior to scanning; we don't
2416            // want to automatically grant runtime permissions for new system apps
2417            if (mPromoteSystemApps) {
2418                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2419                while (pkgSettingIter.hasNext()) {
2420                    PackageSetting ps = pkgSettingIter.next();
2421                    if (isSystemApp(ps)) {
2422                        mExistingSystemPackages.add(ps.name);
2423                    }
2424                }
2425            }
2426
2427            mCacheDir = preparePackageParserCache(mIsUpgrade);
2428
2429            // Set flag to monitor and not change apk file paths when
2430            // scanning install directories.
2431            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2432
2433            if (mIsUpgrade || mFirstBoot) {
2434                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2435            }
2436
2437            // Collect vendor overlay packages. (Do this before scanning any apps.)
2438            // For security and version matching reason, only consider
2439            // overlay packages if they reside in the right directory.
2440            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2441                    | PackageParser.PARSE_IS_SYSTEM
2442                    | PackageParser.PARSE_IS_SYSTEM_DIR
2443                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2444
2445            // Find base frameworks (resource packages without code).
2446            scanDirTracedLI(frameworkDir, mDefParseFlags
2447                    | PackageParser.PARSE_IS_SYSTEM
2448                    | PackageParser.PARSE_IS_SYSTEM_DIR
2449                    | PackageParser.PARSE_IS_PRIVILEGED,
2450                    scanFlags | SCAN_NO_DEX, 0);
2451
2452            // Collected privileged system packages.
2453            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2454            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2455                    | PackageParser.PARSE_IS_SYSTEM
2456                    | PackageParser.PARSE_IS_SYSTEM_DIR
2457                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2458
2459            // Collect ordinary system packages.
2460            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2461            scanDirTracedLI(systemAppDir, mDefParseFlags
2462                    | PackageParser.PARSE_IS_SYSTEM
2463                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2464
2465            // Collect all vendor packages.
2466            File vendorAppDir = new File("/vendor/app");
2467            try {
2468                vendorAppDir = vendorAppDir.getCanonicalFile();
2469            } catch (IOException e) {
2470                // failed to look up canonical path, continue with original one
2471            }
2472            scanDirTracedLI(vendorAppDir, mDefParseFlags
2473                    | PackageParser.PARSE_IS_SYSTEM
2474                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2475
2476            // Collect all OEM packages.
2477            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2478            scanDirTracedLI(oemAppDir, mDefParseFlags
2479                    | PackageParser.PARSE_IS_SYSTEM
2480                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2481
2482            // Prune any system packages that no longer exist.
2483            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2484            if (!mOnlyCore) {
2485                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2486                while (psit.hasNext()) {
2487                    PackageSetting ps = psit.next();
2488
2489                    /*
2490                     * If this is not a system app, it can't be a
2491                     * disable system app.
2492                     */
2493                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2494                        continue;
2495                    }
2496
2497                    /*
2498                     * If the package is scanned, it's not erased.
2499                     */
2500                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2501                    if (scannedPkg != null) {
2502                        /*
2503                         * If the system app is both scanned and in the
2504                         * disabled packages list, then it must have been
2505                         * added via OTA. Remove it from the currently
2506                         * scanned package so the previously user-installed
2507                         * application can be scanned.
2508                         */
2509                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2510                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2511                                    + ps.name + "; removing system app.  Last known codePath="
2512                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2513                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2514                                    + scannedPkg.mVersionCode);
2515                            removePackageLI(scannedPkg, true);
2516                            mExpectingBetter.put(ps.name, ps.codePath);
2517                        }
2518
2519                        continue;
2520                    }
2521
2522                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2523                        psit.remove();
2524                        logCriticalInfo(Log.WARN, "System package " + ps.name
2525                                + " no longer exists; it's data will be wiped");
2526                        // Actual deletion of code and data will be handled by later
2527                        // reconciliation step
2528                    } else {
2529                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2530                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2531                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2532                        }
2533                    }
2534                }
2535            }
2536
2537            //look for any incomplete package installations
2538            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2539            for (int i = 0; i < deletePkgsList.size(); i++) {
2540                // Actual deletion of code and data will be handled by later
2541                // reconciliation step
2542                final String packageName = deletePkgsList.get(i).name;
2543                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2544                synchronized (mPackages) {
2545                    mSettings.removePackageLPw(packageName);
2546                }
2547            }
2548
2549            //delete tmp files
2550            deleteTempPackageFiles();
2551
2552            // Remove any shared userIDs that have no associated packages
2553            mSettings.pruneSharedUsersLPw();
2554
2555            if (!mOnlyCore) {
2556                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2557                        SystemClock.uptimeMillis());
2558                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2559
2560                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2561                        | PackageParser.PARSE_FORWARD_LOCK,
2562                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2563
2564                /**
2565                 * Remove disable package settings for any updated system
2566                 * apps that were removed via an OTA. If they're not a
2567                 * previously-updated app, remove them completely.
2568                 * Otherwise, just revoke their system-level permissions.
2569                 */
2570                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2571                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2572                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2573
2574                    String msg;
2575                    if (deletedPkg == null) {
2576                        msg = "Updated system package " + deletedAppName
2577                                + " no longer exists; it's data will be wiped";
2578                        // Actual deletion of code and data will be handled by later
2579                        // reconciliation step
2580                    } else {
2581                        msg = "Updated system app + " + deletedAppName
2582                                + " no longer present; removing system privileges for "
2583                                + deletedAppName;
2584
2585                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2586
2587                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2588                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2589                    }
2590                    logCriticalInfo(Log.WARN, msg);
2591                }
2592
2593                /**
2594                 * Make sure all system apps that we expected to appear on
2595                 * the userdata partition actually showed up. If they never
2596                 * appeared, crawl back and revive the system version.
2597                 */
2598                for (int i = 0; i < mExpectingBetter.size(); i++) {
2599                    final String packageName = mExpectingBetter.keyAt(i);
2600                    if (!mPackages.containsKey(packageName)) {
2601                        final File scanFile = mExpectingBetter.valueAt(i);
2602
2603                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2604                                + " but never showed up; reverting to system");
2605
2606                        int reparseFlags = mDefParseFlags;
2607                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2608                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2609                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2610                                    | PackageParser.PARSE_IS_PRIVILEGED;
2611                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2612                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2613                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2614                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2615                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2616                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2617                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2618                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2619                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2620                        } else {
2621                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2622                            continue;
2623                        }
2624
2625                        mSettings.enableSystemPackageLPw(packageName);
2626
2627                        try {
2628                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2629                        } catch (PackageManagerException e) {
2630                            Slog.e(TAG, "Failed to parse original system package: "
2631                                    + e.getMessage());
2632                        }
2633                    }
2634                }
2635            }
2636            mExpectingBetter.clear();
2637
2638            // Resolve the storage manager.
2639            mStorageManagerPackage = getStorageManagerPackageName();
2640
2641            // Resolve protected action filters. Only the setup wizard is allowed to
2642            // have a high priority filter for these actions.
2643            mSetupWizardPackage = getSetupWizardPackageName();
2644            if (mProtectedFilters.size() > 0) {
2645                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2646                    Slog.i(TAG, "No setup wizard;"
2647                        + " All protected intents capped to priority 0");
2648                }
2649                for (ActivityIntentInfo filter : mProtectedFilters) {
2650                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2651                        if (DEBUG_FILTERS) {
2652                            Slog.i(TAG, "Found setup wizard;"
2653                                + " allow priority " + filter.getPriority() + ";"
2654                                + " package: " + filter.activity.info.packageName
2655                                + " activity: " + filter.activity.className
2656                                + " priority: " + filter.getPriority());
2657                        }
2658                        // skip setup wizard; allow it to keep the high priority filter
2659                        continue;
2660                    }
2661                    Slog.w(TAG, "Protected action; cap priority to 0;"
2662                            + " package: " + filter.activity.info.packageName
2663                            + " activity: " + filter.activity.className
2664                            + " origPrio: " + filter.getPriority());
2665                    filter.setPriority(0);
2666                }
2667            }
2668            mDeferProtectedFilters = false;
2669            mProtectedFilters.clear();
2670
2671            // Now that we know all of the shared libraries, update all clients to have
2672            // the correct library paths.
2673            updateAllSharedLibrariesLPw(null);
2674
2675            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2676                // NOTE: We ignore potential failures here during a system scan (like
2677                // the rest of the commands above) because there's precious little we
2678                // can do about it. A settings error is reported, though.
2679                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2680            }
2681
2682            // Now that we know all the packages we are keeping,
2683            // read and update their last usage times.
2684            mPackageUsage.read(mPackages);
2685            mCompilerStats.read();
2686
2687            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2688                    SystemClock.uptimeMillis());
2689            Slog.i(TAG, "Time to scan packages: "
2690                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2691                    + " seconds");
2692
2693            // If the platform SDK has changed since the last time we booted,
2694            // we need to re-grant app permission to catch any new ones that
2695            // appear.  This is really a hack, and means that apps can in some
2696            // cases get permissions that the user didn't initially explicitly
2697            // allow...  it would be nice to have some better way to handle
2698            // this situation.
2699            int updateFlags = UPDATE_PERMISSIONS_ALL;
2700            if (ver.sdkVersion != mSdkVersion) {
2701                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2702                        + mSdkVersion + "; regranting permissions for internal storage");
2703                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2704            }
2705            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2706            ver.sdkVersion = mSdkVersion;
2707
2708            // If this is the first boot or an update from pre-M, and it is a normal
2709            // boot, then we need to initialize the default preferred apps across
2710            // all defined users.
2711            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2712                for (UserInfo user : sUserManager.getUsers(true)) {
2713                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2714                    applyFactoryDefaultBrowserLPw(user.id);
2715                    primeDomainVerificationsLPw(user.id);
2716                }
2717            }
2718
2719            // Prepare storage for system user really early during boot,
2720            // since core system apps like SettingsProvider and SystemUI
2721            // can't wait for user to start
2722            final int storageFlags;
2723            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2724                storageFlags = StorageManager.FLAG_STORAGE_DE;
2725            } else {
2726                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2727            }
2728            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2729                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2730                    true /* onlyCoreApps */);
2731            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2732                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2733                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2734                traceLog.traceBegin("AppDataFixup");
2735                try {
2736                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2737                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2738                } catch (InstallerException e) {
2739                    Slog.w(TAG, "Trouble fixing GIDs", e);
2740                }
2741                traceLog.traceEnd();
2742
2743                traceLog.traceBegin("AppDataPrepare");
2744                if (deferPackages == null || deferPackages.isEmpty()) {
2745                    return;
2746                }
2747                int count = 0;
2748                for (String pkgName : deferPackages) {
2749                    PackageParser.Package pkg = null;
2750                    synchronized (mPackages) {
2751                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2752                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2753                            pkg = ps.pkg;
2754                        }
2755                    }
2756                    if (pkg != null) {
2757                        synchronized (mInstallLock) {
2758                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2759                                    true /* maybeMigrateAppData */);
2760                        }
2761                        count++;
2762                    }
2763                }
2764                traceLog.traceEnd();
2765                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2766            }, "prepareAppData");
2767
2768            // If this is first boot after an OTA, and a normal boot, then
2769            // we need to clear code cache directories.
2770            // Note that we do *not* clear the application profiles. These remain valid
2771            // across OTAs and are used to drive profile verification (post OTA) and
2772            // profile compilation (without waiting to collect a fresh set of profiles).
2773            if (mIsUpgrade && !onlyCore) {
2774                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2775                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2776                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2777                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2778                        // No apps are running this early, so no need to freeze
2779                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2780                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2781                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2782                    }
2783                }
2784                ver.fingerprint = Build.FINGERPRINT;
2785            }
2786
2787            checkDefaultBrowser();
2788
2789            // clear only after permissions and other defaults have been updated
2790            mExistingSystemPackages.clear();
2791            mPromoteSystemApps = false;
2792
2793            // All the changes are done during package scanning.
2794            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2795
2796            // can downgrade to reader
2797            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2798            mSettings.writeLPr();
2799            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2800
2801            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2802                    SystemClock.uptimeMillis());
2803
2804            if (!mOnlyCore) {
2805                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2806                mRequiredInstallerPackage = getRequiredInstallerLPr();
2807                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2808                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2809                if (mIntentFilterVerifierComponent != null) {
2810                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2811                            mIntentFilterVerifierComponent);
2812                } else {
2813                    mIntentFilterVerifier = null;
2814                }
2815                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2816                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2817                        SharedLibraryInfo.VERSION_UNDEFINED);
2818                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2819                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2820                        SharedLibraryInfo.VERSION_UNDEFINED);
2821            } else {
2822                mRequiredVerifierPackage = null;
2823                mRequiredInstallerPackage = null;
2824                mRequiredUninstallerPackage = null;
2825                mIntentFilterVerifierComponent = null;
2826                mIntentFilterVerifier = null;
2827                mServicesSystemSharedLibraryPackageName = null;
2828                mSharedSystemSharedLibraryPackageName = null;
2829            }
2830
2831            mInstallerService = new PackageInstallerService(context, this);
2832            final Pair<ComponentName, String> instantAppResolverComponent =
2833                    getInstantAppResolverLPr();
2834            if (instantAppResolverComponent != null) {
2835                if (DEBUG_EPHEMERAL) {
2836                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2837                }
2838                mInstantAppResolverConnection = new EphemeralResolverConnection(
2839                        mContext, instantAppResolverComponent.first,
2840                        instantAppResolverComponent.second);
2841                mInstantAppResolverSettingsComponent =
2842                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2843            } else {
2844                mInstantAppResolverConnection = null;
2845                mInstantAppResolverSettingsComponent = null;
2846            }
2847            updateInstantAppInstallerLocked(null);
2848
2849            // Read and update the usage of dex files.
2850            // Do this at the end of PM init so that all the packages have their
2851            // data directory reconciled.
2852            // At this point we know the code paths of the packages, so we can validate
2853            // the disk file and build the internal cache.
2854            // The usage file is expected to be small so loading and verifying it
2855            // should take a fairly small time compare to the other activities (e.g. package
2856            // scanning).
2857            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2858            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2859            for (int userId : currentUserIds) {
2860                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2861            }
2862            mDexManager.load(userPackages);
2863        } // synchronized (mPackages)
2864        } // synchronized (mInstallLock)
2865
2866        // Now after opening every single application zip, make sure they
2867        // are all flushed.  Not really needed, but keeps things nice and
2868        // tidy.
2869        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2870        Runtime.getRuntime().gc();
2871        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2872
2873        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2874        FallbackCategoryProvider.loadFallbacks();
2875        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2876
2877        // The initial scanning above does many calls into installd while
2878        // holding the mPackages lock, but we're mostly interested in yelling
2879        // once we have a booted system.
2880        mInstaller.setWarnIfHeld(mPackages);
2881
2882        // Expose private service for system components to use.
2883        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2884        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2885    }
2886
2887    private void updateInstantAppInstallerLocked(String modifiedPackage) {
2888        // we're only interested in updating the installer appliction when 1) it's not
2889        // already set or 2) the modified package is the installer
2890        if (mInstantAppInstallerActivity != null
2891                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
2892                        .equals(modifiedPackage)) {
2893            return;
2894        }
2895        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
2896    }
2897
2898    private static File preparePackageParserCache(boolean isUpgrade) {
2899        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2900            return null;
2901        }
2902
2903        // Disable package parsing on eng builds to allow for faster incremental development.
2904        if ("eng".equals(Build.TYPE)) {
2905            return null;
2906        }
2907
2908        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2909            Slog.i(TAG, "Disabling package parser cache due to system property.");
2910            return null;
2911        }
2912
2913        // The base directory for the package parser cache lives under /data/system/.
2914        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2915                "package_cache");
2916        if (cacheBaseDir == null) {
2917            return null;
2918        }
2919
2920        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2921        // This also serves to "GC" unused entries when the package cache version changes (which
2922        // can only happen during upgrades).
2923        if (isUpgrade) {
2924            FileUtils.deleteContents(cacheBaseDir);
2925        }
2926
2927
2928        // Return the versioned package cache directory. This is something like
2929        // "/data/system/package_cache/1"
2930        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2931
2932        // The following is a workaround to aid development on non-numbered userdebug
2933        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2934        // the system partition is newer.
2935        //
2936        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2937        // that starts with "eng." to signify that this is an engineering build and not
2938        // destined for release.
2939        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2940            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2941
2942            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2943            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2944            // in general and should not be used for production changes. In this specific case,
2945            // we know that they will work.
2946            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2947            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2948                FileUtils.deleteContents(cacheBaseDir);
2949                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2950            }
2951        }
2952
2953        return cacheDir;
2954    }
2955
2956    @Override
2957    public boolean isFirstBoot() {
2958        return mFirstBoot;
2959    }
2960
2961    @Override
2962    public boolean isOnlyCoreApps() {
2963        return mOnlyCore;
2964    }
2965
2966    @Override
2967    public boolean isUpgrade() {
2968        return mIsUpgrade;
2969    }
2970
2971    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2972        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2973
2974        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2975                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2976                UserHandle.USER_SYSTEM);
2977        if (matches.size() == 1) {
2978            return matches.get(0).getComponentInfo().packageName;
2979        } else if (matches.size() == 0) {
2980            Log.e(TAG, "There should probably be a verifier, but, none were found");
2981            return null;
2982        }
2983        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2984    }
2985
2986    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2987        synchronized (mPackages) {
2988            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2989            if (libraryEntry == null) {
2990                throw new IllegalStateException("Missing required shared library:" + name);
2991            }
2992            return libraryEntry.apk;
2993        }
2994    }
2995
2996    private @NonNull String getRequiredInstallerLPr() {
2997        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2998        intent.addCategory(Intent.CATEGORY_DEFAULT);
2999        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3000
3001        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3002                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3003                UserHandle.USER_SYSTEM);
3004        if (matches.size() == 1) {
3005            ResolveInfo resolveInfo = matches.get(0);
3006            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3007                throw new RuntimeException("The installer must be a privileged app");
3008            }
3009            return matches.get(0).getComponentInfo().packageName;
3010        } else {
3011            throw new RuntimeException("There must be exactly one installer; found " + matches);
3012        }
3013    }
3014
3015    private @NonNull String getRequiredUninstallerLPr() {
3016        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3017        intent.addCategory(Intent.CATEGORY_DEFAULT);
3018        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3019
3020        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3021                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3022                UserHandle.USER_SYSTEM);
3023        if (resolveInfo == null ||
3024                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3025            throw new RuntimeException("There must be exactly one uninstaller; found "
3026                    + resolveInfo);
3027        }
3028        return resolveInfo.getComponentInfo().packageName;
3029    }
3030
3031    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3032        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3033
3034        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3035                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3036                UserHandle.USER_SYSTEM);
3037        ResolveInfo best = null;
3038        final int N = matches.size();
3039        for (int i = 0; i < N; i++) {
3040            final ResolveInfo cur = matches.get(i);
3041            final String packageName = cur.getComponentInfo().packageName;
3042            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3043                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3044                continue;
3045            }
3046
3047            if (best == null || cur.priority > best.priority) {
3048                best = cur;
3049            }
3050        }
3051
3052        if (best != null) {
3053            return best.getComponentInfo().getComponentName();
3054        }
3055        Slog.w(TAG, "Intent filter verifier not found");
3056        return null;
3057    }
3058
3059    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3060        final String[] packageArray =
3061                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3062        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3063            if (DEBUG_EPHEMERAL) {
3064                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3065            }
3066            return null;
3067        }
3068
3069        final int callingUid = Binder.getCallingUid();
3070        final int resolveFlags =
3071                MATCH_DIRECT_BOOT_AWARE
3072                | MATCH_DIRECT_BOOT_UNAWARE
3073                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3074        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3075        final Intent resolverIntent = new Intent(actionName);
3076        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3077                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3078        // temporarily look for the old action
3079        if (resolvers.size() == 0) {
3080            if (DEBUG_EPHEMERAL) {
3081                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3082            }
3083            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3084            resolverIntent.setAction(actionName);
3085            resolvers = queryIntentServicesInternal(resolverIntent, null,
3086                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3087        }
3088        final int N = resolvers.size();
3089        if (N == 0) {
3090            if (DEBUG_EPHEMERAL) {
3091                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3092            }
3093            return null;
3094        }
3095
3096        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3097        for (int i = 0; i < N; i++) {
3098            final ResolveInfo info = resolvers.get(i);
3099
3100            if (info.serviceInfo == null) {
3101                continue;
3102            }
3103
3104            final String packageName = info.serviceInfo.packageName;
3105            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3106                if (DEBUG_EPHEMERAL) {
3107                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3108                            + " pkg: " + packageName + ", info:" + info);
3109                }
3110                continue;
3111            }
3112
3113            if (DEBUG_EPHEMERAL) {
3114                Slog.v(TAG, "Ephemeral resolver found;"
3115                        + " pkg: " + packageName + ", info:" + info);
3116            }
3117            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3118        }
3119        if (DEBUG_EPHEMERAL) {
3120            Slog.v(TAG, "Ephemeral resolver NOT found");
3121        }
3122        return null;
3123    }
3124
3125    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3126        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3127        intent.addCategory(Intent.CATEGORY_DEFAULT);
3128        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3129
3130        final int resolveFlags =
3131                MATCH_DIRECT_BOOT_AWARE
3132                | MATCH_DIRECT_BOOT_UNAWARE
3133                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3134        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3135                resolveFlags, UserHandle.USER_SYSTEM);
3136        // temporarily look for the old action
3137        if (matches.isEmpty()) {
3138            if (DEBUG_EPHEMERAL) {
3139                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3140            }
3141            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3142            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3143                    resolveFlags, UserHandle.USER_SYSTEM);
3144        }
3145        Iterator<ResolveInfo> iter = matches.iterator();
3146        while (iter.hasNext()) {
3147            final ResolveInfo rInfo = iter.next();
3148            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3149            if (ps != null) {
3150                final PermissionsState permissionsState = ps.getPermissionsState();
3151                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3152                    continue;
3153                }
3154            }
3155            iter.remove();
3156        }
3157        if (matches.size() == 0) {
3158            return null;
3159        } else if (matches.size() == 1) {
3160            return (ActivityInfo) matches.get(0).getComponentInfo();
3161        } else {
3162            throw new RuntimeException(
3163                    "There must be at most one ephemeral installer; found " + matches);
3164        }
3165    }
3166
3167    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3168            @NonNull ComponentName resolver) {
3169        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3170                .addCategory(Intent.CATEGORY_DEFAULT)
3171                .setPackage(resolver.getPackageName());
3172        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3173        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3174                UserHandle.USER_SYSTEM);
3175        // temporarily look for the old action
3176        if (matches.isEmpty()) {
3177            if (DEBUG_EPHEMERAL) {
3178                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3179            }
3180            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3181            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3182                    UserHandle.USER_SYSTEM);
3183        }
3184        if (matches.isEmpty()) {
3185            return null;
3186        }
3187        return matches.get(0).getComponentInfo().getComponentName();
3188    }
3189
3190    private void primeDomainVerificationsLPw(int userId) {
3191        if (DEBUG_DOMAIN_VERIFICATION) {
3192            Slog.d(TAG, "Priming domain verifications in user " + userId);
3193        }
3194
3195        SystemConfig systemConfig = SystemConfig.getInstance();
3196        ArraySet<String> packages = systemConfig.getLinkedApps();
3197
3198        for (String packageName : packages) {
3199            PackageParser.Package pkg = mPackages.get(packageName);
3200            if (pkg != null) {
3201                if (!pkg.isSystemApp()) {
3202                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3203                    continue;
3204                }
3205
3206                ArraySet<String> domains = null;
3207                for (PackageParser.Activity a : pkg.activities) {
3208                    for (ActivityIntentInfo filter : a.intents) {
3209                        if (hasValidDomains(filter)) {
3210                            if (domains == null) {
3211                                domains = new ArraySet<String>();
3212                            }
3213                            domains.addAll(filter.getHostsList());
3214                        }
3215                    }
3216                }
3217
3218                if (domains != null && domains.size() > 0) {
3219                    if (DEBUG_DOMAIN_VERIFICATION) {
3220                        Slog.v(TAG, "      + " + packageName);
3221                    }
3222                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3223                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3224                    // and then 'always' in the per-user state actually used for intent resolution.
3225                    final IntentFilterVerificationInfo ivi;
3226                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3227                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3228                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3229                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3230                } else {
3231                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3232                            + "' does not handle web links");
3233                }
3234            } else {
3235                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3236            }
3237        }
3238
3239        scheduleWritePackageRestrictionsLocked(userId);
3240        scheduleWriteSettingsLocked();
3241    }
3242
3243    private void applyFactoryDefaultBrowserLPw(int userId) {
3244        // The default browser app's package name is stored in a string resource,
3245        // with a product-specific overlay used for vendor customization.
3246        String browserPkg = mContext.getResources().getString(
3247                com.android.internal.R.string.default_browser);
3248        if (!TextUtils.isEmpty(browserPkg)) {
3249            // non-empty string => required to be a known package
3250            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3251            if (ps == null) {
3252                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3253                browserPkg = null;
3254            } else {
3255                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3256            }
3257        }
3258
3259        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3260        // default.  If there's more than one, just leave everything alone.
3261        if (browserPkg == null) {
3262            calculateDefaultBrowserLPw(userId);
3263        }
3264    }
3265
3266    private void calculateDefaultBrowserLPw(int userId) {
3267        List<String> allBrowsers = resolveAllBrowserApps(userId);
3268        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3269        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3270    }
3271
3272    private List<String> resolveAllBrowserApps(int userId) {
3273        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3274        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3275                PackageManager.MATCH_ALL, userId);
3276
3277        final int count = list.size();
3278        List<String> result = new ArrayList<String>(count);
3279        for (int i=0; i<count; i++) {
3280            ResolveInfo info = list.get(i);
3281            if (info.activityInfo == null
3282                    || !info.handleAllWebDataURI
3283                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3284                    || result.contains(info.activityInfo.packageName)) {
3285                continue;
3286            }
3287            result.add(info.activityInfo.packageName);
3288        }
3289
3290        return result;
3291    }
3292
3293    private boolean packageIsBrowser(String packageName, int userId) {
3294        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3295                PackageManager.MATCH_ALL, userId);
3296        final int N = list.size();
3297        for (int i = 0; i < N; i++) {
3298            ResolveInfo info = list.get(i);
3299            if (packageName.equals(info.activityInfo.packageName)) {
3300                return true;
3301            }
3302        }
3303        return false;
3304    }
3305
3306    private void checkDefaultBrowser() {
3307        final int myUserId = UserHandle.myUserId();
3308        final String packageName = getDefaultBrowserPackageName(myUserId);
3309        if (packageName != null) {
3310            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3311            if (info == null) {
3312                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3313                synchronized (mPackages) {
3314                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3315                }
3316            }
3317        }
3318    }
3319
3320    @Override
3321    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3322            throws RemoteException {
3323        try {
3324            return super.onTransact(code, data, reply, flags);
3325        } catch (RuntimeException e) {
3326            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3327                Slog.wtf(TAG, "Package Manager Crash", e);
3328            }
3329            throw e;
3330        }
3331    }
3332
3333    static int[] appendInts(int[] cur, int[] add) {
3334        if (add == null) return cur;
3335        if (cur == null) return add;
3336        final int N = add.length;
3337        for (int i=0; i<N; i++) {
3338            cur = appendInt(cur, add[i]);
3339        }
3340        return cur;
3341    }
3342
3343    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3344        if (!sUserManager.exists(userId)) return null;
3345        if (ps == null) {
3346            return null;
3347        }
3348        final PackageParser.Package p = ps.pkg;
3349        if (p == null) {
3350            return null;
3351        }
3352        // Filter out ephemeral app metadata:
3353        //   * The system/shell/root can see metadata for any app
3354        //   * An installed app can see metadata for 1) other installed apps
3355        //     and 2) ephemeral apps that have explicitly interacted with it
3356        //   * Ephemeral apps can only see their own data and exposed installed apps
3357        //   * Holding a signature permission allows seeing instant apps
3358        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3359        if (callingAppId != Process.SYSTEM_UID
3360                && callingAppId != Process.SHELL_UID
3361                && callingAppId != Process.ROOT_UID
3362                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3363                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3364            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3365            if (instantAppPackageName != null) {
3366                // ephemeral apps can only get information on themselves or
3367                // installed apps that are exposed.
3368                if (!instantAppPackageName.equals(p.packageName)
3369                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3370                    return null;
3371                }
3372            } else {
3373                if (ps.getInstantApp(userId)) {
3374                    // only get access to the ephemeral app if we've been granted access
3375                    if (!mInstantAppRegistry.isInstantAccessGranted(
3376                            userId, callingAppId, ps.appId)) {
3377                        return null;
3378                    }
3379                }
3380            }
3381        }
3382
3383        final PermissionsState permissionsState = ps.getPermissionsState();
3384
3385        // Compute GIDs only if requested
3386        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3387                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3388        // Compute granted permissions only if package has requested permissions
3389        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3390                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3391        final PackageUserState state = ps.readUserState(userId);
3392
3393        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3394                && ps.isSystem()) {
3395            flags |= MATCH_ANY_USER;
3396        }
3397
3398        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3399                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3400
3401        if (packageInfo == null) {
3402            return null;
3403        }
3404
3405        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3406
3407        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3408                resolveExternalPackageNameLPr(p);
3409
3410        return packageInfo;
3411    }
3412
3413    @Override
3414    public void checkPackageStartable(String packageName, int userId) {
3415        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3416
3417        synchronized (mPackages) {
3418            final PackageSetting ps = mSettings.mPackages.get(packageName);
3419            if (ps == null) {
3420                throw new SecurityException("Package " + packageName + " was not found!");
3421            }
3422
3423            if (!ps.getInstalled(userId)) {
3424                throw new SecurityException(
3425                        "Package " + packageName + " was not installed for user " + userId + "!");
3426            }
3427
3428            if (mSafeMode && !ps.isSystem()) {
3429                throw new SecurityException("Package " + packageName + " not a system app!");
3430            }
3431
3432            if (mFrozenPackages.contains(packageName)) {
3433                throw new SecurityException("Package " + packageName + " is currently frozen!");
3434            }
3435
3436            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3437                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3438                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3439            }
3440        }
3441    }
3442
3443    @Override
3444    public boolean isPackageAvailable(String packageName, int userId) {
3445        if (!sUserManager.exists(userId)) return false;
3446        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3447                false /* requireFullPermission */, false /* checkShell */, "is package available");
3448        synchronized (mPackages) {
3449            PackageParser.Package p = mPackages.get(packageName);
3450            if (p != null) {
3451                final PackageSetting ps = (PackageSetting) p.mExtras;
3452                if (ps != null) {
3453                    final PackageUserState state = ps.readUserState(userId);
3454                    if (state != null) {
3455                        return PackageParser.isAvailable(state);
3456                    }
3457                }
3458            }
3459        }
3460        return false;
3461    }
3462
3463    @Override
3464    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3465        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3466                flags, userId);
3467    }
3468
3469    @Override
3470    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3471            int flags, int userId) {
3472        return getPackageInfoInternal(versionedPackage.getPackageName(),
3473                // TODO: We will change version code to long, so in the new API it is long
3474                (int) versionedPackage.getVersionCode(), flags, userId);
3475    }
3476
3477    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3478            int flags, int userId) {
3479        if (!sUserManager.exists(userId)) return null;
3480        flags = updateFlagsForPackage(flags, userId, packageName);
3481        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3482                false /* requireFullPermission */, false /* checkShell */, "get package info");
3483
3484        // reader
3485        synchronized (mPackages) {
3486            // Normalize package name to handle renamed packages and static libs
3487            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3488
3489            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3490            if (matchFactoryOnly) {
3491                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3492                if (ps != null) {
3493                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3494                        return null;
3495                    }
3496                    return generatePackageInfo(ps, flags, userId);
3497                }
3498            }
3499
3500            PackageParser.Package p = mPackages.get(packageName);
3501            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3502                return null;
3503            }
3504            if (DEBUG_PACKAGE_INFO)
3505                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3506            if (p != null) {
3507                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3508                        Binder.getCallingUid(), userId)) {
3509                    return null;
3510                }
3511                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3512            }
3513            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3514                final PackageSetting ps = mSettings.mPackages.get(packageName);
3515                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3516                    return null;
3517                }
3518                return generatePackageInfo(ps, flags, userId);
3519            }
3520        }
3521        return null;
3522    }
3523
3524
3525    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3526        // System/shell/root get to see all static libs
3527        final int appId = UserHandle.getAppId(uid);
3528        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3529                || appId == Process.ROOT_UID) {
3530            return false;
3531        }
3532
3533        // No package means no static lib as it is always on internal storage
3534        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3535            return false;
3536        }
3537
3538        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3539                ps.pkg.staticSharedLibVersion);
3540        if (libEntry == null) {
3541            return false;
3542        }
3543
3544        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3545        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3546        if (uidPackageNames == null) {
3547            return true;
3548        }
3549
3550        for (String uidPackageName : uidPackageNames) {
3551            if (ps.name.equals(uidPackageName)) {
3552                return false;
3553            }
3554            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3555            if (uidPs != null) {
3556                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3557                        libEntry.info.getName());
3558                if (index < 0) {
3559                    continue;
3560                }
3561                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3562                    return false;
3563                }
3564            }
3565        }
3566        return true;
3567    }
3568
3569    @Override
3570    public String[] currentToCanonicalPackageNames(String[] names) {
3571        String[] out = new String[names.length];
3572        // reader
3573        synchronized (mPackages) {
3574            for (int i=names.length-1; i>=0; i--) {
3575                PackageSetting ps = mSettings.mPackages.get(names[i]);
3576                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3577            }
3578        }
3579        return out;
3580    }
3581
3582    @Override
3583    public String[] canonicalToCurrentPackageNames(String[] names) {
3584        String[] out = new String[names.length];
3585        // reader
3586        synchronized (mPackages) {
3587            for (int i=names.length-1; i>=0; i--) {
3588                String cur = mSettings.getRenamedPackageLPr(names[i]);
3589                out[i] = cur != null ? cur : names[i];
3590            }
3591        }
3592        return out;
3593    }
3594
3595    @Override
3596    public int getPackageUid(String packageName, int flags, int userId) {
3597        if (!sUserManager.exists(userId)) return -1;
3598        flags = updateFlagsForPackage(flags, userId, packageName);
3599        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3600                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3601
3602        // reader
3603        synchronized (mPackages) {
3604            final PackageParser.Package p = mPackages.get(packageName);
3605            if (p != null && p.isMatch(flags)) {
3606                return UserHandle.getUid(userId, p.applicationInfo.uid);
3607            }
3608            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3609                final PackageSetting ps = mSettings.mPackages.get(packageName);
3610                if (ps != null && ps.isMatch(flags)) {
3611                    return UserHandle.getUid(userId, ps.appId);
3612                }
3613            }
3614        }
3615
3616        return -1;
3617    }
3618
3619    @Override
3620    public int[] getPackageGids(String packageName, int flags, int userId) {
3621        if (!sUserManager.exists(userId)) return null;
3622        flags = updateFlagsForPackage(flags, userId, packageName);
3623        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3624                false /* requireFullPermission */, false /* checkShell */,
3625                "getPackageGids");
3626
3627        // reader
3628        synchronized (mPackages) {
3629            final PackageParser.Package p = mPackages.get(packageName);
3630            if (p != null && p.isMatch(flags)) {
3631                PackageSetting ps = (PackageSetting) p.mExtras;
3632                // TODO: Shouldn't this be checking for package installed state for userId and
3633                // return null?
3634                return ps.getPermissionsState().computeGids(userId);
3635            }
3636            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3637                final PackageSetting ps = mSettings.mPackages.get(packageName);
3638                if (ps != null && ps.isMatch(flags)) {
3639                    return ps.getPermissionsState().computeGids(userId);
3640                }
3641            }
3642        }
3643
3644        return null;
3645    }
3646
3647    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3648        if (bp.perm != null) {
3649            return PackageParser.generatePermissionInfo(bp.perm, flags);
3650        }
3651        PermissionInfo pi = new PermissionInfo();
3652        pi.name = bp.name;
3653        pi.packageName = bp.sourcePackage;
3654        pi.nonLocalizedLabel = bp.name;
3655        pi.protectionLevel = bp.protectionLevel;
3656        return pi;
3657    }
3658
3659    @Override
3660    public PermissionInfo getPermissionInfo(String name, int flags) {
3661        // reader
3662        synchronized (mPackages) {
3663            final BasePermission p = mSettings.mPermissions.get(name);
3664            if (p != null) {
3665                return generatePermissionInfo(p, flags);
3666            }
3667            return null;
3668        }
3669    }
3670
3671    @Override
3672    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3673            int flags) {
3674        // reader
3675        synchronized (mPackages) {
3676            if (group != null && !mPermissionGroups.containsKey(group)) {
3677                // This is thrown as NameNotFoundException
3678                return null;
3679            }
3680
3681            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3682            for (BasePermission p : mSettings.mPermissions.values()) {
3683                if (group == null) {
3684                    if (p.perm == null || p.perm.info.group == null) {
3685                        out.add(generatePermissionInfo(p, flags));
3686                    }
3687                } else {
3688                    if (p.perm != null && group.equals(p.perm.info.group)) {
3689                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3690                    }
3691                }
3692            }
3693            return new ParceledListSlice<>(out);
3694        }
3695    }
3696
3697    @Override
3698    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3699        // reader
3700        synchronized (mPackages) {
3701            return PackageParser.generatePermissionGroupInfo(
3702                    mPermissionGroups.get(name), flags);
3703        }
3704    }
3705
3706    @Override
3707    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3708        // reader
3709        synchronized (mPackages) {
3710            final int N = mPermissionGroups.size();
3711            ArrayList<PermissionGroupInfo> out
3712                    = new ArrayList<PermissionGroupInfo>(N);
3713            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3714                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3715            }
3716            return new ParceledListSlice<>(out);
3717        }
3718    }
3719
3720    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3721            int uid, int userId) {
3722        if (!sUserManager.exists(userId)) return null;
3723        PackageSetting ps = mSettings.mPackages.get(packageName);
3724        if (ps != null) {
3725            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3726                return null;
3727            }
3728            if (ps.pkg == null) {
3729                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3730                if (pInfo != null) {
3731                    return pInfo.applicationInfo;
3732                }
3733                return null;
3734            }
3735            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3736                    ps.readUserState(userId), userId);
3737            if (ai != null) {
3738                rebaseEnabledOverlays(ai, userId);
3739                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3740            }
3741            return ai;
3742        }
3743        return null;
3744    }
3745
3746    @Override
3747    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3748        if (!sUserManager.exists(userId)) return null;
3749        flags = updateFlagsForApplication(flags, userId, packageName);
3750        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3751                false /* requireFullPermission */, false /* checkShell */, "get application info");
3752
3753        // writer
3754        synchronized (mPackages) {
3755            // Normalize package name to handle renamed packages and static libs
3756            packageName = resolveInternalPackageNameLPr(packageName,
3757                    PackageManager.VERSION_CODE_HIGHEST);
3758
3759            PackageParser.Package p = mPackages.get(packageName);
3760            if (DEBUG_PACKAGE_INFO) Log.v(
3761                    TAG, "getApplicationInfo " + packageName
3762                    + ": " + p);
3763            if (p != null) {
3764                PackageSetting ps = mSettings.mPackages.get(packageName);
3765                if (ps == null) return null;
3766                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3767                    return null;
3768                }
3769                // Note: isEnabledLP() does not apply here - always return info
3770                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3771                        p, flags, ps.readUserState(userId), userId);
3772                if (ai != null) {
3773                    rebaseEnabledOverlays(ai, userId);
3774                    ai.packageName = resolveExternalPackageNameLPr(p);
3775                }
3776                return ai;
3777            }
3778            if ("android".equals(packageName)||"system".equals(packageName)) {
3779                return mAndroidApplication;
3780            }
3781            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3782                // Already generates the external package name
3783                return generateApplicationInfoFromSettingsLPw(packageName,
3784                        Binder.getCallingUid(), flags, userId);
3785            }
3786        }
3787        return null;
3788    }
3789
3790    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3791        List<String> paths = new ArrayList<>();
3792        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3793            mEnabledOverlayPaths.get(userId);
3794        if (userSpecificOverlays != null) {
3795            if (!"android".equals(ai.packageName)) {
3796                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3797                if (frameworkOverlays != null) {
3798                    paths.addAll(frameworkOverlays);
3799                }
3800            }
3801
3802            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3803            if (appOverlays != null) {
3804                paths.addAll(appOverlays);
3805            }
3806        }
3807        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3808    }
3809
3810    private String normalizePackageNameLPr(String packageName) {
3811        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3812        return normalizedPackageName != null ? normalizedPackageName : packageName;
3813    }
3814
3815    @Override
3816    public void deletePreloadsFileCache() {
3817        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3818            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3819        }
3820        File dir = Environment.getDataPreloadsFileCacheDirectory();
3821        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3822        FileUtils.deleteContents(dir);
3823    }
3824
3825    @Override
3826    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3827            final IPackageDataObserver observer) {
3828        mContext.enforceCallingOrSelfPermission(
3829                android.Manifest.permission.CLEAR_APP_CACHE, null);
3830        mHandler.post(() -> {
3831            boolean success = false;
3832            try {
3833                freeStorage(volumeUuid, freeStorageSize, 0);
3834                success = true;
3835            } catch (IOException e) {
3836                Slog.w(TAG, e);
3837            }
3838            if (observer != null) {
3839                try {
3840                    observer.onRemoveCompleted(null, success);
3841                } catch (RemoteException e) {
3842                    Slog.w(TAG, e);
3843                }
3844            }
3845        });
3846    }
3847
3848    @Override
3849    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3850            final IntentSender pi) {
3851        mContext.enforceCallingOrSelfPermission(
3852                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3853        mHandler.post(() -> {
3854            boolean success = false;
3855            try {
3856                freeStorage(volumeUuid, freeStorageSize, 0);
3857                success = true;
3858            } catch (IOException e) {
3859                Slog.w(TAG, e);
3860            }
3861            if (pi != null) {
3862                try {
3863                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3864                } catch (SendIntentException e) {
3865                    Slog.w(TAG, e);
3866                }
3867            }
3868        });
3869    }
3870
3871    /**
3872     * Blocking call to clear various types of cached data across the system
3873     * until the requested bytes are available.
3874     */
3875    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3876        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3877        final File file = storage.findPathForUuid(volumeUuid);
3878        if (file.getUsableSpace() >= bytes) return;
3879
3880        if (ENABLE_FREE_CACHE_V2) {
3881            final boolean aggressive = (storageFlags
3882                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3883            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3884                    volumeUuid);
3885
3886            // 1. Pre-flight to determine if we have any chance to succeed
3887            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3888            if (internalVolume && (aggressive || SystemProperties
3889                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3890                deletePreloadsFileCache();
3891                if (file.getUsableSpace() >= bytes) return;
3892            }
3893
3894            // 3. Consider parsed APK data (aggressive only)
3895            if (internalVolume && aggressive) {
3896                FileUtils.deleteContents(mCacheDir);
3897                if (file.getUsableSpace() >= bytes) return;
3898            }
3899
3900            // 4. Consider cached app data (above quotas)
3901            try {
3902                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3903            } catch (InstallerException ignored) {
3904            }
3905            if (file.getUsableSpace() >= bytes) return;
3906
3907            // 5. Consider shared libraries with refcount=0 and age>2h
3908            // 6. Consider dexopt output (aggressive only)
3909            // 7. Consider ephemeral apps not used in last week
3910
3911            // 8. Consider cached app data (below quotas)
3912            try {
3913                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3914                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3915            } catch (InstallerException ignored) {
3916            }
3917            if (file.getUsableSpace() >= bytes) return;
3918
3919            // 9. Consider DropBox entries
3920            // 10. Consider ephemeral cookies
3921
3922        } else {
3923            try {
3924                mInstaller.freeCache(volumeUuid, bytes, 0);
3925            } catch (InstallerException ignored) {
3926            }
3927            if (file.getUsableSpace() >= bytes) return;
3928        }
3929
3930        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3931    }
3932
3933    /**
3934     * Update given flags based on encryption status of current user.
3935     */
3936    private int updateFlags(int flags, int userId) {
3937        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3938                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3939            // Caller expressed an explicit opinion about what encryption
3940            // aware/unaware components they want to see, so fall through and
3941            // give them what they want
3942        } else {
3943            // Caller expressed no opinion, so match based on user state
3944            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3945                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3946            } else {
3947                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3948            }
3949        }
3950        return flags;
3951    }
3952
3953    private UserManagerInternal getUserManagerInternal() {
3954        if (mUserManagerInternal == null) {
3955            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3956        }
3957        return mUserManagerInternal;
3958    }
3959
3960    private DeviceIdleController.LocalService getDeviceIdleController() {
3961        if (mDeviceIdleController == null) {
3962            mDeviceIdleController =
3963                    LocalServices.getService(DeviceIdleController.LocalService.class);
3964        }
3965        return mDeviceIdleController;
3966    }
3967
3968    /**
3969     * Update given flags when being used to request {@link PackageInfo}.
3970     */
3971    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3972        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3973        boolean triaged = true;
3974        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3975                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3976            // Caller is asking for component details, so they'd better be
3977            // asking for specific encryption matching behavior, or be triaged
3978            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3979                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3980                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3981                triaged = false;
3982            }
3983        }
3984        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3985                | PackageManager.MATCH_SYSTEM_ONLY
3986                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3987            triaged = false;
3988        }
3989        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3990            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3991                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3992                    + Debug.getCallers(5));
3993        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3994                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3995            // If the caller wants all packages and has a restricted profile associated with it,
3996            // then match all users. This is to make sure that launchers that need to access work
3997            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3998            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3999            flags |= PackageManager.MATCH_ANY_USER;
4000        }
4001        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4002            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4003                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4004        }
4005        return updateFlags(flags, userId);
4006    }
4007
4008    /**
4009     * Update given flags when being used to request {@link ApplicationInfo}.
4010     */
4011    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4012        return updateFlagsForPackage(flags, userId, cookie);
4013    }
4014
4015    /**
4016     * Update given flags when being used to request {@link ComponentInfo}.
4017     */
4018    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4019        if (cookie instanceof Intent) {
4020            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4021                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4022            }
4023        }
4024
4025        boolean triaged = true;
4026        // Caller is asking for component details, so they'd better be
4027        // asking for specific encryption matching behavior, or be triaged
4028        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4029                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4030                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4031            triaged = false;
4032        }
4033        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4034            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4035                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4036        }
4037
4038        return updateFlags(flags, userId);
4039    }
4040
4041    /**
4042     * Update given intent when being used to request {@link ResolveInfo}.
4043     */
4044    private Intent updateIntentForResolve(Intent intent) {
4045        if (intent.getSelector() != null) {
4046            intent = intent.getSelector();
4047        }
4048        if (DEBUG_PREFERRED) {
4049            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4050        }
4051        return intent;
4052    }
4053
4054    /**
4055     * Update given flags when being used to request {@link ResolveInfo}.
4056     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4057     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4058     * flag set. However, this flag is only honoured in three circumstances:
4059     * <ul>
4060     * <li>when called from a system process</li>
4061     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4062     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4063     * action and a {@code android.intent.category.BROWSABLE} category</li>
4064     * </ul>
4065     */
4066    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4067            boolean includeInstantApps) {
4068        // Safe mode means we shouldn't match any third-party components
4069        if (mSafeMode) {
4070            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4071        }
4072        if (getInstantAppPackageName(callingUid) != null) {
4073            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4074            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4075            flags |= PackageManager.MATCH_INSTANT;
4076        } else {
4077            // Otherwise, prevent leaking ephemeral components
4078            final boolean isSpecialProcess =
4079                    callingUid == Process.SYSTEM_UID
4080                    || callingUid == Process.SHELL_UID
4081                    || callingUid == 0;
4082            final boolean allowMatchInstant =
4083                    (includeInstantApps
4084                            && Intent.ACTION_VIEW.equals(intent.getAction())
4085                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4086                            && hasWebURI(intent))
4087                    || isSpecialProcess
4088                    || mContext.checkCallingOrSelfPermission(
4089                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4090            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4091            if (!allowMatchInstant) {
4092                flags &= ~PackageManager.MATCH_INSTANT;
4093            }
4094        }
4095        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4096    }
4097
4098    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4099            int userId) {
4100        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4101        if (ret != null) {
4102            rebaseEnabledOverlays(ret.applicationInfo, userId);
4103        }
4104        return ret;
4105    }
4106
4107    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4108            PackageUserState state, int userId) {
4109        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4110        if (ai != null) {
4111            rebaseEnabledOverlays(ai.applicationInfo, userId);
4112        }
4113        return ai;
4114    }
4115
4116    @Override
4117    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4118        if (!sUserManager.exists(userId)) return null;
4119        flags = updateFlagsForComponent(flags, userId, component);
4120        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4121                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4122        synchronized (mPackages) {
4123            PackageParser.Activity a = mActivities.mActivities.get(component);
4124
4125            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4126            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4127                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4128                if (ps == null) return null;
4129                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4130            }
4131            if (mResolveComponentName.equals(component)) {
4132                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4133                        userId);
4134            }
4135        }
4136        return null;
4137    }
4138
4139    @Override
4140    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4141            String resolvedType) {
4142        synchronized (mPackages) {
4143            if (component.equals(mResolveComponentName)) {
4144                // The resolver supports EVERYTHING!
4145                return true;
4146            }
4147            PackageParser.Activity a = mActivities.mActivities.get(component);
4148            if (a == null) {
4149                return false;
4150            }
4151            for (int i=0; i<a.intents.size(); i++) {
4152                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4153                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4154                    return true;
4155                }
4156            }
4157            return false;
4158        }
4159    }
4160
4161    @Override
4162    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4163        if (!sUserManager.exists(userId)) return null;
4164        flags = updateFlagsForComponent(flags, userId, component);
4165        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4166                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4167        synchronized (mPackages) {
4168            PackageParser.Activity a = mReceivers.mActivities.get(component);
4169            if (DEBUG_PACKAGE_INFO) Log.v(
4170                TAG, "getReceiverInfo " + component + ": " + a);
4171            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4172                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4173                if (ps == null) return null;
4174                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4175            }
4176        }
4177        return null;
4178    }
4179
4180    @Override
4181    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4182        if (!sUserManager.exists(userId)) return null;
4183        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4184
4185        flags = updateFlagsForPackage(flags, userId, null);
4186
4187        final boolean canSeeStaticLibraries =
4188                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4189                        == PERMISSION_GRANTED
4190                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4191                        == PERMISSION_GRANTED
4192                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4193                        == PERMISSION_GRANTED
4194                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4195                        == PERMISSION_GRANTED;
4196
4197        synchronized (mPackages) {
4198            List<SharedLibraryInfo> result = null;
4199
4200            final int libCount = mSharedLibraries.size();
4201            for (int i = 0; i < libCount; i++) {
4202                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4203                if (versionedLib == null) {
4204                    continue;
4205                }
4206
4207                final int versionCount = versionedLib.size();
4208                for (int j = 0; j < versionCount; j++) {
4209                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4210                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4211                        break;
4212                    }
4213                    final long identity = Binder.clearCallingIdentity();
4214                    try {
4215                        // TODO: We will change version code to long, so in the new API it is long
4216                        PackageInfo packageInfo = getPackageInfoVersioned(
4217                                libInfo.getDeclaringPackage(), flags, userId);
4218                        if (packageInfo == null) {
4219                            continue;
4220                        }
4221                    } finally {
4222                        Binder.restoreCallingIdentity(identity);
4223                    }
4224
4225                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4226                            // TODO: Remove cast for lib version once internally we support longs.
4227                            (int) libInfo.getVersion(), libInfo.getType(),
4228                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4229                            flags, userId));
4230
4231                    if (result == null) {
4232                        result = new ArrayList<>();
4233                    }
4234                    result.add(resLibInfo);
4235                }
4236            }
4237
4238            return result != null ? new ParceledListSlice<>(result) : null;
4239        }
4240    }
4241
4242    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4243            SharedLibraryInfo libInfo, int flags, int userId) {
4244        List<VersionedPackage> versionedPackages = null;
4245        final int packageCount = mSettings.mPackages.size();
4246        for (int i = 0; i < packageCount; i++) {
4247            PackageSetting ps = mSettings.mPackages.valueAt(i);
4248
4249            if (ps == null) {
4250                continue;
4251            }
4252
4253            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4254                continue;
4255            }
4256
4257            final String libName = libInfo.getName();
4258            if (libInfo.isStatic()) {
4259                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4260                if (libIdx < 0) {
4261                    continue;
4262                }
4263                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4264                    continue;
4265                }
4266                if (versionedPackages == null) {
4267                    versionedPackages = new ArrayList<>();
4268                }
4269                // If the dependent is a static shared lib, use the public package name
4270                String dependentPackageName = ps.name;
4271                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4272                    dependentPackageName = ps.pkg.manifestPackageName;
4273                }
4274                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4275            } else if (ps.pkg != null) {
4276                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4277                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4278                    if (versionedPackages == null) {
4279                        versionedPackages = new ArrayList<>();
4280                    }
4281                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4282                }
4283            }
4284        }
4285
4286        return versionedPackages;
4287    }
4288
4289    @Override
4290    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4291        if (!sUserManager.exists(userId)) return null;
4292        flags = updateFlagsForComponent(flags, userId, component);
4293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4294                false /* requireFullPermission */, false /* checkShell */, "get service info");
4295        synchronized (mPackages) {
4296            PackageParser.Service s = mServices.mServices.get(component);
4297            if (DEBUG_PACKAGE_INFO) Log.v(
4298                TAG, "getServiceInfo " + component + ": " + s);
4299            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4300                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4301                if (ps == null) return null;
4302                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4303                        ps.readUserState(userId), userId);
4304                if (si != null) {
4305                    rebaseEnabledOverlays(si.applicationInfo, userId);
4306                }
4307                return si;
4308            }
4309        }
4310        return null;
4311    }
4312
4313    @Override
4314    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4315        if (!sUserManager.exists(userId)) return null;
4316        flags = updateFlagsForComponent(flags, userId, component);
4317        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4318                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4319        synchronized (mPackages) {
4320            PackageParser.Provider p = mProviders.mProviders.get(component);
4321            if (DEBUG_PACKAGE_INFO) Log.v(
4322                TAG, "getProviderInfo " + component + ": " + p);
4323            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4324                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4325                if (ps == null) return null;
4326                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4327                        ps.readUserState(userId), userId);
4328                if (pi != null) {
4329                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4330                }
4331                return pi;
4332            }
4333        }
4334        return null;
4335    }
4336
4337    @Override
4338    public String[] getSystemSharedLibraryNames() {
4339        synchronized (mPackages) {
4340            Set<String> libs = null;
4341            final int libCount = mSharedLibraries.size();
4342            for (int i = 0; i < libCount; i++) {
4343                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4344                if (versionedLib == null) {
4345                    continue;
4346                }
4347                final int versionCount = versionedLib.size();
4348                for (int j = 0; j < versionCount; j++) {
4349                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4350                    if (!libEntry.info.isStatic()) {
4351                        if (libs == null) {
4352                            libs = new ArraySet<>();
4353                        }
4354                        libs.add(libEntry.info.getName());
4355                        break;
4356                    }
4357                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4358                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4359                            UserHandle.getUserId(Binder.getCallingUid()))) {
4360                        if (libs == null) {
4361                            libs = new ArraySet<>();
4362                        }
4363                        libs.add(libEntry.info.getName());
4364                        break;
4365                    }
4366                }
4367            }
4368
4369            if (libs != null) {
4370                String[] libsArray = new String[libs.size()];
4371                libs.toArray(libsArray);
4372                return libsArray;
4373            }
4374
4375            return null;
4376        }
4377    }
4378
4379    @Override
4380    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4381        synchronized (mPackages) {
4382            return mServicesSystemSharedLibraryPackageName;
4383        }
4384    }
4385
4386    @Override
4387    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4388        synchronized (mPackages) {
4389            return mSharedSystemSharedLibraryPackageName;
4390        }
4391    }
4392
4393    private void updateSequenceNumberLP(String packageName, int[] userList) {
4394        for (int i = userList.length - 1; i >= 0; --i) {
4395            final int userId = userList[i];
4396            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4397            if (changedPackages == null) {
4398                changedPackages = new SparseArray<>();
4399                mChangedPackages.put(userId, changedPackages);
4400            }
4401            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4402            if (sequenceNumbers == null) {
4403                sequenceNumbers = new HashMap<>();
4404                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4405            }
4406            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4407            if (sequenceNumber != null) {
4408                changedPackages.remove(sequenceNumber);
4409            }
4410            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4411            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4412        }
4413        mChangedPackagesSequenceNumber++;
4414    }
4415
4416    @Override
4417    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4418        synchronized (mPackages) {
4419            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4420                return null;
4421            }
4422            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4423            if (changedPackages == null) {
4424                return null;
4425            }
4426            final List<String> packageNames =
4427                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4428            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4429                final String packageName = changedPackages.get(i);
4430                if (packageName != null) {
4431                    packageNames.add(packageName);
4432                }
4433            }
4434            return packageNames.isEmpty()
4435                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4436        }
4437    }
4438
4439    @Override
4440    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4441        ArrayList<FeatureInfo> res;
4442        synchronized (mAvailableFeatures) {
4443            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4444            res.addAll(mAvailableFeatures.values());
4445        }
4446        final FeatureInfo fi = new FeatureInfo();
4447        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4448                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4449        res.add(fi);
4450
4451        return new ParceledListSlice<>(res);
4452    }
4453
4454    @Override
4455    public boolean hasSystemFeature(String name, int version) {
4456        synchronized (mAvailableFeatures) {
4457            final FeatureInfo feat = mAvailableFeatures.get(name);
4458            if (feat == null) {
4459                return false;
4460            } else {
4461                return feat.version >= version;
4462            }
4463        }
4464    }
4465
4466    @Override
4467    public int checkPermission(String permName, String pkgName, int userId) {
4468        if (!sUserManager.exists(userId)) {
4469            return PackageManager.PERMISSION_DENIED;
4470        }
4471
4472        synchronized (mPackages) {
4473            final PackageParser.Package p = mPackages.get(pkgName);
4474            if (p != null && p.mExtras != null) {
4475                final PackageSetting ps = (PackageSetting) p.mExtras;
4476                final PermissionsState permissionsState = ps.getPermissionsState();
4477                if (permissionsState.hasPermission(permName, userId)) {
4478                    return PackageManager.PERMISSION_GRANTED;
4479                }
4480                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4481                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4482                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4483                    return PackageManager.PERMISSION_GRANTED;
4484                }
4485            }
4486        }
4487
4488        return PackageManager.PERMISSION_DENIED;
4489    }
4490
4491    @Override
4492    public int checkUidPermission(String permName, int uid) {
4493        final int userId = UserHandle.getUserId(uid);
4494
4495        if (!sUserManager.exists(userId)) {
4496            return PackageManager.PERMISSION_DENIED;
4497        }
4498
4499        synchronized (mPackages) {
4500            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4501            if (obj != null) {
4502                final SettingBase ps = (SettingBase) obj;
4503                final PermissionsState permissionsState = ps.getPermissionsState();
4504                if (permissionsState.hasPermission(permName, userId)) {
4505                    return PackageManager.PERMISSION_GRANTED;
4506                }
4507                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4508                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4509                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4510                    return PackageManager.PERMISSION_GRANTED;
4511                }
4512            } else {
4513                ArraySet<String> perms = mSystemPermissions.get(uid);
4514                if (perms != null) {
4515                    if (perms.contains(permName)) {
4516                        return PackageManager.PERMISSION_GRANTED;
4517                    }
4518                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4519                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4520                        return PackageManager.PERMISSION_GRANTED;
4521                    }
4522                }
4523            }
4524        }
4525
4526        return PackageManager.PERMISSION_DENIED;
4527    }
4528
4529    @Override
4530    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4531        if (UserHandle.getCallingUserId() != userId) {
4532            mContext.enforceCallingPermission(
4533                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4534                    "isPermissionRevokedByPolicy for user " + userId);
4535        }
4536
4537        if (checkPermission(permission, packageName, userId)
4538                == PackageManager.PERMISSION_GRANTED) {
4539            return false;
4540        }
4541
4542        final long identity = Binder.clearCallingIdentity();
4543        try {
4544            final int flags = getPermissionFlags(permission, packageName, userId);
4545            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4546        } finally {
4547            Binder.restoreCallingIdentity(identity);
4548        }
4549    }
4550
4551    @Override
4552    public String getPermissionControllerPackageName() {
4553        synchronized (mPackages) {
4554            return mRequiredInstallerPackage;
4555        }
4556    }
4557
4558    /**
4559     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4560     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4561     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4562     * @param message the message to log on security exception
4563     */
4564    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4565            boolean checkShell, String message) {
4566        if (userId < 0) {
4567            throw new IllegalArgumentException("Invalid userId " + userId);
4568        }
4569        if (checkShell) {
4570            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4571        }
4572        if (userId == UserHandle.getUserId(callingUid)) return;
4573        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4574            if (requireFullPermission) {
4575                mContext.enforceCallingOrSelfPermission(
4576                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4577            } else {
4578                try {
4579                    mContext.enforceCallingOrSelfPermission(
4580                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4581                } catch (SecurityException se) {
4582                    mContext.enforceCallingOrSelfPermission(
4583                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4584                }
4585            }
4586        }
4587    }
4588
4589    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4590        if (callingUid == Process.SHELL_UID) {
4591            if (userHandle >= 0
4592                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4593                throw new SecurityException("Shell does not have permission to access user "
4594                        + userHandle);
4595            } else if (userHandle < 0) {
4596                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4597                        + Debug.getCallers(3));
4598            }
4599        }
4600    }
4601
4602    private BasePermission findPermissionTreeLP(String permName) {
4603        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4604            if (permName.startsWith(bp.name) &&
4605                    permName.length() > bp.name.length() &&
4606                    permName.charAt(bp.name.length()) == '.') {
4607                return bp;
4608            }
4609        }
4610        return null;
4611    }
4612
4613    private BasePermission checkPermissionTreeLP(String permName) {
4614        if (permName != null) {
4615            BasePermission bp = findPermissionTreeLP(permName);
4616            if (bp != null) {
4617                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4618                    return bp;
4619                }
4620                throw new SecurityException("Calling uid "
4621                        + Binder.getCallingUid()
4622                        + " is not allowed to add to permission tree "
4623                        + bp.name + " owned by uid " + bp.uid);
4624            }
4625        }
4626        throw new SecurityException("No permission tree found for " + permName);
4627    }
4628
4629    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4630        if (s1 == null) {
4631            return s2 == null;
4632        }
4633        if (s2 == null) {
4634            return false;
4635        }
4636        if (s1.getClass() != s2.getClass()) {
4637            return false;
4638        }
4639        return s1.equals(s2);
4640    }
4641
4642    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4643        if (pi1.icon != pi2.icon) return false;
4644        if (pi1.logo != pi2.logo) return false;
4645        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4646        if (!compareStrings(pi1.name, pi2.name)) return false;
4647        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4648        // We'll take care of setting this one.
4649        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4650        // These are not currently stored in settings.
4651        //if (!compareStrings(pi1.group, pi2.group)) return false;
4652        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4653        //if (pi1.labelRes != pi2.labelRes) return false;
4654        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4655        return true;
4656    }
4657
4658    int permissionInfoFootprint(PermissionInfo info) {
4659        int size = info.name.length();
4660        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4661        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4662        return size;
4663    }
4664
4665    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4666        int size = 0;
4667        for (BasePermission perm : mSettings.mPermissions.values()) {
4668            if (perm.uid == tree.uid) {
4669                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4670            }
4671        }
4672        return size;
4673    }
4674
4675    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4676        // We calculate the max size of permissions defined by this uid and throw
4677        // if that plus the size of 'info' would exceed our stated maximum.
4678        if (tree.uid != Process.SYSTEM_UID) {
4679            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4680            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4681                throw new SecurityException("Permission tree size cap exceeded");
4682            }
4683        }
4684    }
4685
4686    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4687        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4688            throw new SecurityException("Label must be specified in permission");
4689        }
4690        BasePermission tree = checkPermissionTreeLP(info.name);
4691        BasePermission bp = mSettings.mPermissions.get(info.name);
4692        boolean added = bp == null;
4693        boolean changed = true;
4694        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4695        if (added) {
4696            enforcePermissionCapLocked(info, tree);
4697            bp = new BasePermission(info.name, tree.sourcePackage,
4698                    BasePermission.TYPE_DYNAMIC);
4699        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4700            throw new SecurityException(
4701                    "Not allowed to modify non-dynamic permission "
4702                    + info.name);
4703        } else {
4704            if (bp.protectionLevel == fixedLevel
4705                    && bp.perm.owner.equals(tree.perm.owner)
4706                    && bp.uid == tree.uid
4707                    && comparePermissionInfos(bp.perm.info, info)) {
4708                changed = false;
4709            }
4710        }
4711        bp.protectionLevel = fixedLevel;
4712        info = new PermissionInfo(info);
4713        info.protectionLevel = fixedLevel;
4714        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4715        bp.perm.info.packageName = tree.perm.info.packageName;
4716        bp.uid = tree.uid;
4717        if (added) {
4718            mSettings.mPermissions.put(info.name, bp);
4719        }
4720        if (changed) {
4721            if (!async) {
4722                mSettings.writeLPr();
4723            } else {
4724                scheduleWriteSettingsLocked();
4725            }
4726        }
4727        return added;
4728    }
4729
4730    @Override
4731    public boolean addPermission(PermissionInfo info) {
4732        synchronized (mPackages) {
4733            return addPermissionLocked(info, false);
4734        }
4735    }
4736
4737    @Override
4738    public boolean addPermissionAsync(PermissionInfo info) {
4739        synchronized (mPackages) {
4740            return addPermissionLocked(info, true);
4741        }
4742    }
4743
4744    @Override
4745    public void removePermission(String name) {
4746        synchronized (mPackages) {
4747            checkPermissionTreeLP(name);
4748            BasePermission bp = mSettings.mPermissions.get(name);
4749            if (bp != null) {
4750                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4751                    throw new SecurityException(
4752                            "Not allowed to modify non-dynamic permission "
4753                            + name);
4754                }
4755                mSettings.mPermissions.remove(name);
4756                mSettings.writeLPr();
4757            }
4758        }
4759    }
4760
4761    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4762            BasePermission bp) {
4763        int index = pkg.requestedPermissions.indexOf(bp.name);
4764        if (index == -1) {
4765            throw new SecurityException("Package " + pkg.packageName
4766                    + " has not requested permission " + bp.name);
4767        }
4768        if (!bp.isRuntime() && !bp.isDevelopment()) {
4769            throw new SecurityException("Permission " + bp.name
4770                    + " is not a changeable permission type");
4771        }
4772    }
4773
4774    @Override
4775    public void grantRuntimePermission(String packageName, String name, final int userId) {
4776        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4777    }
4778
4779    private void grantRuntimePermission(String packageName, String name, final int userId,
4780            boolean overridePolicy) {
4781        if (!sUserManager.exists(userId)) {
4782            Log.e(TAG, "No such user:" + userId);
4783            return;
4784        }
4785
4786        mContext.enforceCallingOrSelfPermission(
4787                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4788                "grantRuntimePermission");
4789
4790        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4791                true /* requireFullPermission */, true /* checkShell */,
4792                "grantRuntimePermission");
4793
4794        final int uid;
4795        final SettingBase sb;
4796
4797        synchronized (mPackages) {
4798            final PackageParser.Package pkg = mPackages.get(packageName);
4799            if (pkg == null) {
4800                throw new IllegalArgumentException("Unknown package: " + packageName);
4801            }
4802
4803            final BasePermission bp = mSettings.mPermissions.get(name);
4804            if (bp == null) {
4805                throw new IllegalArgumentException("Unknown permission: " + name);
4806            }
4807
4808            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4809
4810            // If a permission review is required for legacy apps we represent
4811            // their permissions as always granted runtime ones since we need
4812            // to keep the review required permission flag per user while an
4813            // install permission's state is shared across all users.
4814            if (mPermissionReviewRequired
4815                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4816                    && bp.isRuntime()) {
4817                return;
4818            }
4819
4820            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4821            sb = (SettingBase) pkg.mExtras;
4822            if (sb == null) {
4823                throw new IllegalArgumentException("Unknown package: " + packageName);
4824            }
4825
4826            final PermissionsState permissionsState = sb.getPermissionsState();
4827
4828            final int flags = permissionsState.getPermissionFlags(name, userId);
4829            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4830                throw new SecurityException("Cannot grant system fixed permission "
4831                        + name + " for package " + packageName);
4832            }
4833            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4834                throw new SecurityException("Cannot grant policy fixed permission "
4835                        + name + " for package " + packageName);
4836            }
4837
4838            if (bp.isDevelopment()) {
4839                // Development permissions must be handled specially, since they are not
4840                // normal runtime permissions.  For now they apply to all users.
4841                if (permissionsState.grantInstallPermission(bp) !=
4842                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4843                    scheduleWriteSettingsLocked();
4844                }
4845                return;
4846            }
4847
4848            final PackageSetting ps = mSettings.mPackages.get(packageName);
4849            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4850                throw new SecurityException("Cannot grant non-ephemeral permission"
4851                        + name + " for package " + packageName);
4852            }
4853
4854            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4855                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4856                return;
4857            }
4858
4859            final int result = permissionsState.grantRuntimePermission(bp, userId);
4860            switch (result) {
4861                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4862                    return;
4863                }
4864
4865                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4866                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4867                    mHandler.post(new Runnable() {
4868                        @Override
4869                        public void run() {
4870                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4871                        }
4872                    });
4873                }
4874                break;
4875            }
4876
4877            if (bp.isRuntime()) {
4878                logPermissionGranted(mContext, name, packageName);
4879            }
4880
4881            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4882
4883            // Not critical if that is lost - app has to request again.
4884            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4885        }
4886
4887        // Only need to do this if user is initialized. Otherwise it's a new user
4888        // and there are no processes running as the user yet and there's no need
4889        // to make an expensive call to remount processes for the changed permissions.
4890        if (READ_EXTERNAL_STORAGE.equals(name)
4891                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4892            final long token = Binder.clearCallingIdentity();
4893            try {
4894                if (sUserManager.isInitialized(userId)) {
4895                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4896                            StorageManagerInternal.class);
4897                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4898                }
4899            } finally {
4900                Binder.restoreCallingIdentity(token);
4901            }
4902        }
4903    }
4904
4905    @Override
4906    public void revokeRuntimePermission(String packageName, String name, int userId) {
4907        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4908    }
4909
4910    private void revokeRuntimePermission(String packageName, String name, int userId,
4911            boolean overridePolicy) {
4912        if (!sUserManager.exists(userId)) {
4913            Log.e(TAG, "No such user:" + userId);
4914            return;
4915        }
4916
4917        mContext.enforceCallingOrSelfPermission(
4918                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4919                "revokeRuntimePermission");
4920
4921        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4922                true /* requireFullPermission */, true /* checkShell */,
4923                "revokeRuntimePermission");
4924
4925        final int appId;
4926
4927        synchronized (mPackages) {
4928            final PackageParser.Package pkg = mPackages.get(packageName);
4929            if (pkg == null) {
4930                throw new IllegalArgumentException("Unknown package: " + packageName);
4931            }
4932
4933            final BasePermission bp = mSettings.mPermissions.get(name);
4934            if (bp == null) {
4935                throw new IllegalArgumentException("Unknown permission: " + name);
4936            }
4937
4938            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4939
4940            // If a permission review is required for legacy apps we represent
4941            // their permissions as always granted runtime ones since we need
4942            // to keep the review required permission flag per user while an
4943            // install permission's state is shared across all users.
4944            if (mPermissionReviewRequired
4945                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4946                    && bp.isRuntime()) {
4947                return;
4948            }
4949
4950            SettingBase sb = (SettingBase) pkg.mExtras;
4951            if (sb == null) {
4952                throw new IllegalArgumentException("Unknown package: " + packageName);
4953            }
4954
4955            final PermissionsState permissionsState = sb.getPermissionsState();
4956
4957            final int flags = permissionsState.getPermissionFlags(name, userId);
4958            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4959                throw new SecurityException("Cannot revoke system fixed permission "
4960                        + name + " for package " + packageName);
4961            }
4962            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4963                throw new SecurityException("Cannot revoke policy fixed permission "
4964                        + name + " for package " + packageName);
4965            }
4966
4967            if (bp.isDevelopment()) {
4968                // Development permissions must be handled specially, since they are not
4969                // normal runtime permissions.  For now they apply to all users.
4970                if (permissionsState.revokeInstallPermission(bp) !=
4971                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4972                    scheduleWriteSettingsLocked();
4973                }
4974                return;
4975            }
4976
4977            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4978                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4979                return;
4980            }
4981
4982            if (bp.isRuntime()) {
4983                logPermissionRevoked(mContext, name, packageName);
4984            }
4985
4986            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4987
4988            // Critical, after this call app should never have the permission.
4989            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4990
4991            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4992        }
4993
4994        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4995    }
4996
4997    /**
4998     * Get the first event id for the permission.
4999     *
5000     * <p>There are four events for each permission: <ul>
5001     *     <li>Request permission: first id + 0</li>
5002     *     <li>Grant permission: first id + 1</li>
5003     *     <li>Request for permission denied: first id + 2</li>
5004     *     <li>Revoke permission: first id + 3</li>
5005     * </ul></p>
5006     *
5007     * @param name name of the permission
5008     *
5009     * @return The first event id for the permission
5010     */
5011    private static int getBaseEventId(@NonNull String name) {
5012        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5013
5014        if (eventIdIndex == -1) {
5015            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5016                    || "user".equals(Build.TYPE)) {
5017                Log.i(TAG, "Unknown permission " + name);
5018
5019                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5020            } else {
5021                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5022                //
5023                // Also update
5024                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5025                // - metrics_constants.proto
5026                throw new IllegalStateException("Unknown permission " + name);
5027            }
5028        }
5029
5030        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5031    }
5032
5033    /**
5034     * Log that a permission was revoked.
5035     *
5036     * @param context Context of the caller
5037     * @param name name of the permission
5038     * @param packageName package permission if for
5039     */
5040    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5041            @NonNull String packageName) {
5042        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5043    }
5044
5045    /**
5046     * Log that a permission request was granted.
5047     *
5048     * @param context Context of the caller
5049     * @param name name of the permission
5050     * @param packageName package permission if for
5051     */
5052    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5053            @NonNull String packageName) {
5054        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5055    }
5056
5057    @Override
5058    public void resetRuntimePermissions() {
5059        mContext.enforceCallingOrSelfPermission(
5060                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5061                "revokeRuntimePermission");
5062
5063        int callingUid = Binder.getCallingUid();
5064        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5065            mContext.enforceCallingOrSelfPermission(
5066                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5067                    "resetRuntimePermissions");
5068        }
5069
5070        synchronized (mPackages) {
5071            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5072            for (int userId : UserManagerService.getInstance().getUserIds()) {
5073                final int packageCount = mPackages.size();
5074                for (int i = 0; i < packageCount; i++) {
5075                    PackageParser.Package pkg = mPackages.valueAt(i);
5076                    if (!(pkg.mExtras instanceof PackageSetting)) {
5077                        continue;
5078                    }
5079                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5080                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5081                }
5082            }
5083        }
5084    }
5085
5086    @Override
5087    public int getPermissionFlags(String name, String packageName, int userId) {
5088        if (!sUserManager.exists(userId)) {
5089            return 0;
5090        }
5091
5092        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5093
5094        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5095                true /* requireFullPermission */, false /* checkShell */,
5096                "getPermissionFlags");
5097
5098        synchronized (mPackages) {
5099            final PackageParser.Package pkg = mPackages.get(packageName);
5100            if (pkg == null) {
5101                return 0;
5102            }
5103
5104            final BasePermission bp = mSettings.mPermissions.get(name);
5105            if (bp == null) {
5106                return 0;
5107            }
5108
5109            SettingBase sb = (SettingBase) pkg.mExtras;
5110            if (sb == null) {
5111                return 0;
5112            }
5113
5114            PermissionsState permissionsState = sb.getPermissionsState();
5115            return permissionsState.getPermissionFlags(name, userId);
5116        }
5117    }
5118
5119    @Override
5120    public void updatePermissionFlags(String name, String packageName, int flagMask,
5121            int flagValues, int userId) {
5122        if (!sUserManager.exists(userId)) {
5123            return;
5124        }
5125
5126        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5127
5128        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5129                true /* requireFullPermission */, true /* checkShell */,
5130                "updatePermissionFlags");
5131
5132        // Only the system can change these flags and nothing else.
5133        if (getCallingUid() != Process.SYSTEM_UID) {
5134            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5135            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5136            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5137            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5138            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5139        }
5140
5141        synchronized (mPackages) {
5142            final PackageParser.Package pkg = mPackages.get(packageName);
5143            if (pkg == null) {
5144                throw new IllegalArgumentException("Unknown package: " + packageName);
5145            }
5146
5147            final BasePermission bp = mSettings.mPermissions.get(name);
5148            if (bp == null) {
5149                throw new IllegalArgumentException("Unknown permission: " + name);
5150            }
5151
5152            SettingBase sb = (SettingBase) pkg.mExtras;
5153            if (sb == null) {
5154                throw new IllegalArgumentException("Unknown package: " + packageName);
5155            }
5156
5157            PermissionsState permissionsState = sb.getPermissionsState();
5158
5159            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5160
5161            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5162                // Install and runtime permissions are stored in different places,
5163                // so figure out what permission changed and persist the change.
5164                if (permissionsState.getInstallPermissionState(name) != null) {
5165                    scheduleWriteSettingsLocked();
5166                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5167                        || hadState) {
5168                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5169                }
5170            }
5171        }
5172    }
5173
5174    /**
5175     * Update the permission flags for all packages and runtime permissions of a user in order
5176     * to allow device or profile owner to remove POLICY_FIXED.
5177     */
5178    @Override
5179    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5180        if (!sUserManager.exists(userId)) {
5181            return;
5182        }
5183
5184        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5185
5186        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5187                true /* requireFullPermission */, true /* checkShell */,
5188                "updatePermissionFlagsForAllApps");
5189
5190        // Only the system can change system fixed flags.
5191        if (getCallingUid() != Process.SYSTEM_UID) {
5192            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5193            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5194        }
5195
5196        synchronized (mPackages) {
5197            boolean changed = false;
5198            final int packageCount = mPackages.size();
5199            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5200                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5201                SettingBase sb = (SettingBase) pkg.mExtras;
5202                if (sb == null) {
5203                    continue;
5204                }
5205                PermissionsState permissionsState = sb.getPermissionsState();
5206                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5207                        userId, flagMask, flagValues);
5208            }
5209            if (changed) {
5210                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5211            }
5212        }
5213    }
5214
5215    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5216        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5217                != PackageManager.PERMISSION_GRANTED
5218            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5219                != PackageManager.PERMISSION_GRANTED) {
5220            throw new SecurityException(message + " requires "
5221                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5222                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5223        }
5224    }
5225
5226    @Override
5227    public boolean shouldShowRequestPermissionRationale(String permissionName,
5228            String packageName, int userId) {
5229        if (UserHandle.getCallingUserId() != userId) {
5230            mContext.enforceCallingPermission(
5231                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5232                    "canShowRequestPermissionRationale for user " + userId);
5233        }
5234
5235        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5236        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5237            return false;
5238        }
5239
5240        if (checkPermission(permissionName, packageName, userId)
5241                == PackageManager.PERMISSION_GRANTED) {
5242            return false;
5243        }
5244
5245        final int flags;
5246
5247        final long identity = Binder.clearCallingIdentity();
5248        try {
5249            flags = getPermissionFlags(permissionName,
5250                    packageName, userId);
5251        } finally {
5252            Binder.restoreCallingIdentity(identity);
5253        }
5254
5255        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5256                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5257                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5258
5259        if ((flags & fixedFlags) != 0) {
5260            return false;
5261        }
5262
5263        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5264    }
5265
5266    @Override
5267    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5268        mContext.enforceCallingOrSelfPermission(
5269                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5270                "addOnPermissionsChangeListener");
5271
5272        synchronized (mPackages) {
5273            mOnPermissionChangeListeners.addListenerLocked(listener);
5274        }
5275    }
5276
5277    @Override
5278    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5279        synchronized (mPackages) {
5280            mOnPermissionChangeListeners.removeListenerLocked(listener);
5281        }
5282    }
5283
5284    @Override
5285    public boolean isProtectedBroadcast(String actionName) {
5286        synchronized (mPackages) {
5287            if (mProtectedBroadcasts.contains(actionName)) {
5288                return true;
5289            } else if (actionName != null) {
5290                // TODO: remove these terrible hacks
5291                if (actionName.startsWith("android.net.netmon.lingerExpired")
5292                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5293                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5294                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5295                    return true;
5296                }
5297            }
5298        }
5299        return false;
5300    }
5301
5302    @Override
5303    public int checkSignatures(String pkg1, String pkg2) {
5304        synchronized (mPackages) {
5305            final PackageParser.Package p1 = mPackages.get(pkg1);
5306            final PackageParser.Package p2 = mPackages.get(pkg2);
5307            if (p1 == null || p1.mExtras == null
5308                    || p2 == null || p2.mExtras == null) {
5309                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5310            }
5311            return compareSignatures(p1.mSignatures, p2.mSignatures);
5312        }
5313    }
5314
5315    @Override
5316    public int checkUidSignatures(int uid1, int uid2) {
5317        // Map to base uids.
5318        uid1 = UserHandle.getAppId(uid1);
5319        uid2 = UserHandle.getAppId(uid2);
5320        // reader
5321        synchronized (mPackages) {
5322            Signature[] s1;
5323            Signature[] s2;
5324            Object obj = mSettings.getUserIdLPr(uid1);
5325            if (obj != null) {
5326                if (obj instanceof SharedUserSetting) {
5327                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5328                } else if (obj instanceof PackageSetting) {
5329                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5330                } else {
5331                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5332                }
5333            } else {
5334                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5335            }
5336            obj = mSettings.getUserIdLPr(uid2);
5337            if (obj != null) {
5338                if (obj instanceof SharedUserSetting) {
5339                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5340                } else if (obj instanceof PackageSetting) {
5341                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5342                } else {
5343                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5344                }
5345            } else {
5346                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5347            }
5348            return compareSignatures(s1, s2);
5349        }
5350    }
5351
5352    /**
5353     * This method should typically only be used when granting or revoking
5354     * permissions, since the app may immediately restart after this call.
5355     * <p>
5356     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5357     * guard your work against the app being relaunched.
5358     */
5359    private void killUid(int appId, int userId, String reason) {
5360        final long identity = Binder.clearCallingIdentity();
5361        try {
5362            IActivityManager am = ActivityManager.getService();
5363            if (am != null) {
5364                try {
5365                    am.killUid(appId, userId, reason);
5366                } catch (RemoteException e) {
5367                    /* ignore - same process */
5368                }
5369            }
5370        } finally {
5371            Binder.restoreCallingIdentity(identity);
5372        }
5373    }
5374
5375    /**
5376     * Compares two sets of signatures. Returns:
5377     * <br />
5378     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5379     * <br />
5380     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5381     * <br />
5382     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5383     * <br />
5384     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5385     * <br />
5386     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5387     */
5388    static int compareSignatures(Signature[] s1, Signature[] s2) {
5389        if (s1 == null) {
5390            return s2 == null
5391                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5392                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5393        }
5394
5395        if (s2 == null) {
5396            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5397        }
5398
5399        if (s1.length != s2.length) {
5400            return PackageManager.SIGNATURE_NO_MATCH;
5401        }
5402
5403        // Since both signature sets are of size 1, we can compare without HashSets.
5404        if (s1.length == 1) {
5405            return s1[0].equals(s2[0]) ?
5406                    PackageManager.SIGNATURE_MATCH :
5407                    PackageManager.SIGNATURE_NO_MATCH;
5408        }
5409
5410        ArraySet<Signature> set1 = new ArraySet<Signature>();
5411        for (Signature sig : s1) {
5412            set1.add(sig);
5413        }
5414        ArraySet<Signature> set2 = new ArraySet<Signature>();
5415        for (Signature sig : s2) {
5416            set2.add(sig);
5417        }
5418        // Make sure s2 contains all signatures in s1.
5419        if (set1.equals(set2)) {
5420            return PackageManager.SIGNATURE_MATCH;
5421        }
5422        return PackageManager.SIGNATURE_NO_MATCH;
5423    }
5424
5425    /**
5426     * If the database version for this type of package (internal storage or
5427     * external storage) is less than the version where package signatures
5428     * were updated, return true.
5429     */
5430    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5431        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5432        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5433    }
5434
5435    /**
5436     * Used for backward compatibility to make sure any packages with
5437     * certificate chains get upgraded to the new style. {@code existingSigs}
5438     * will be in the old format (since they were stored on disk from before the
5439     * system upgrade) and {@code scannedSigs} will be in the newer format.
5440     */
5441    private int compareSignaturesCompat(PackageSignatures existingSigs,
5442            PackageParser.Package scannedPkg) {
5443        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5444            return PackageManager.SIGNATURE_NO_MATCH;
5445        }
5446
5447        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5448        for (Signature sig : existingSigs.mSignatures) {
5449            existingSet.add(sig);
5450        }
5451        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5452        for (Signature sig : scannedPkg.mSignatures) {
5453            try {
5454                Signature[] chainSignatures = sig.getChainSignatures();
5455                for (Signature chainSig : chainSignatures) {
5456                    scannedCompatSet.add(chainSig);
5457                }
5458            } catch (CertificateEncodingException e) {
5459                scannedCompatSet.add(sig);
5460            }
5461        }
5462        /*
5463         * Make sure the expanded scanned set contains all signatures in the
5464         * existing one.
5465         */
5466        if (scannedCompatSet.equals(existingSet)) {
5467            // Migrate the old signatures to the new scheme.
5468            existingSigs.assignSignatures(scannedPkg.mSignatures);
5469            // The new KeySets will be re-added later in the scanning process.
5470            synchronized (mPackages) {
5471                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5472            }
5473            return PackageManager.SIGNATURE_MATCH;
5474        }
5475        return PackageManager.SIGNATURE_NO_MATCH;
5476    }
5477
5478    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5479        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5480        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5481    }
5482
5483    private int compareSignaturesRecover(PackageSignatures existingSigs,
5484            PackageParser.Package scannedPkg) {
5485        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5486            return PackageManager.SIGNATURE_NO_MATCH;
5487        }
5488
5489        String msg = null;
5490        try {
5491            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5492                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5493                        + scannedPkg.packageName);
5494                return PackageManager.SIGNATURE_MATCH;
5495            }
5496        } catch (CertificateException e) {
5497            msg = e.getMessage();
5498        }
5499
5500        logCriticalInfo(Log.INFO,
5501                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5502        return PackageManager.SIGNATURE_NO_MATCH;
5503    }
5504
5505    @Override
5506    public List<String> getAllPackages() {
5507        synchronized (mPackages) {
5508            return new ArrayList<String>(mPackages.keySet());
5509        }
5510    }
5511
5512    @Override
5513    public String[] getPackagesForUid(int uid) {
5514        final int userId = UserHandle.getUserId(uid);
5515        uid = UserHandle.getAppId(uid);
5516        // reader
5517        synchronized (mPackages) {
5518            Object obj = mSettings.getUserIdLPr(uid);
5519            if (obj instanceof SharedUserSetting) {
5520                final SharedUserSetting sus = (SharedUserSetting) obj;
5521                final int N = sus.packages.size();
5522                String[] res = new String[N];
5523                final Iterator<PackageSetting> it = sus.packages.iterator();
5524                int i = 0;
5525                while (it.hasNext()) {
5526                    PackageSetting ps = it.next();
5527                    if (ps.getInstalled(userId)) {
5528                        res[i++] = ps.name;
5529                    } else {
5530                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5531                    }
5532                }
5533                return res;
5534            } else if (obj instanceof PackageSetting) {
5535                final PackageSetting ps = (PackageSetting) obj;
5536                if (ps.getInstalled(userId)) {
5537                    return new String[]{ps.name};
5538                }
5539            }
5540        }
5541        return null;
5542    }
5543
5544    @Override
5545    public String getNameForUid(int uid) {
5546        // reader
5547        synchronized (mPackages) {
5548            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5549            if (obj instanceof SharedUserSetting) {
5550                final SharedUserSetting sus = (SharedUserSetting) obj;
5551                return sus.name + ":" + sus.userId;
5552            } else if (obj instanceof PackageSetting) {
5553                final PackageSetting ps = (PackageSetting) obj;
5554                return ps.name;
5555            }
5556        }
5557        return null;
5558    }
5559
5560    @Override
5561    public int getUidForSharedUser(String sharedUserName) {
5562        if(sharedUserName == null) {
5563            return -1;
5564        }
5565        // reader
5566        synchronized (mPackages) {
5567            SharedUserSetting suid;
5568            try {
5569                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5570                if (suid != null) {
5571                    return suid.userId;
5572                }
5573            } catch (PackageManagerException ignore) {
5574                // can't happen, but, still need to catch it
5575            }
5576            return -1;
5577        }
5578    }
5579
5580    @Override
5581    public int getFlagsForUid(int uid) {
5582        synchronized (mPackages) {
5583            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5584            if (obj instanceof SharedUserSetting) {
5585                final SharedUserSetting sus = (SharedUserSetting) obj;
5586                return sus.pkgFlags;
5587            } else if (obj instanceof PackageSetting) {
5588                final PackageSetting ps = (PackageSetting) obj;
5589                return ps.pkgFlags;
5590            }
5591        }
5592        return 0;
5593    }
5594
5595    @Override
5596    public int getPrivateFlagsForUid(int uid) {
5597        synchronized (mPackages) {
5598            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5599            if (obj instanceof SharedUserSetting) {
5600                final SharedUserSetting sus = (SharedUserSetting) obj;
5601                return sus.pkgPrivateFlags;
5602            } else if (obj instanceof PackageSetting) {
5603                final PackageSetting ps = (PackageSetting) obj;
5604                return ps.pkgPrivateFlags;
5605            }
5606        }
5607        return 0;
5608    }
5609
5610    @Override
5611    public boolean isUidPrivileged(int uid) {
5612        uid = UserHandle.getAppId(uid);
5613        // reader
5614        synchronized (mPackages) {
5615            Object obj = mSettings.getUserIdLPr(uid);
5616            if (obj instanceof SharedUserSetting) {
5617                final SharedUserSetting sus = (SharedUserSetting) obj;
5618                final Iterator<PackageSetting> it = sus.packages.iterator();
5619                while (it.hasNext()) {
5620                    if (it.next().isPrivileged()) {
5621                        return true;
5622                    }
5623                }
5624            } else if (obj instanceof PackageSetting) {
5625                final PackageSetting ps = (PackageSetting) obj;
5626                return ps.isPrivileged();
5627            }
5628        }
5629        return false;
5630    }
5631
5632    @Override
5633    public String[] getAppOpPermissionPackages(String permissionName) {
5634        synchronized (mPackages) {
5635            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5636            if (pkgs == null) {
5637                return null;
5638            }
5639            return pkgs.toArray(new String[pkgs.size()]);
5640        }
5641    }
5642
5643    @Override
5644    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5645            int flags, int userId) {
5646        return resolveIntentInternal(
5647                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5648    }
5649
5650    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5651            int flags, int userId, boolean includeInstantApps) {
5652        try {
5653            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5654
5655            if (!sUserManager.exists(userId)) return null;
5656            final int callingUid = Binder.getCallingUid();
5657            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5658            enforceCrossUserPermission(callingUid, userId,
5659                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5660
5661            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5662            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5663                    flags, userId, includeInstantApps);
5664            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5665
5666            final ResolveInfo bestChoice =
5667                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5668            return bestChoice;
5669        } finally {
5670            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5671        }
5672    }
5673
5674    @Override
5675    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5676        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5677            throw new SecurityException(
5678                    "findPersistentPreferredActivity can only be run by the system");
5679        }
5680        if (!sUserManager.exists(userId)) {
5681            return null;
5682        }
5683        final int callingUid = Binder.getCallingUid();
5684        intent = updateIntentForResolve(intent);
5685        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5686        final int flags = updateFlagsForResolve(
5687                0, userId, intent, callingUid, false /*includeInstantApps*/);
5688        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5689                userId);
5690        synchronized (mPackages) {
5691            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5692                    userId);
5693        }
5694    }
5695
5696    @Override
5697    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5698            IntentFilter filter, int match, ComponentName activity) {
5699        final int userId = UserHandle.getCallingUserId();
5700        if (DEBUG_PREFERRED) {
5701            Log.v(TAG, "setLastChosenActivity intent=" + intent
5702                + " resolvedType=" + resolvedType
5703                + " flags=" + flags
5704                + " filter=" + filter
5705                + " match=" + match
5706                + " activity=" + activity);
5707            filter.dump(new PrintStreamPrinter(System.out), "    ");
5708        }
5709        intent.setComponent(null);
5710        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5711                userId);
5712        // Find any earlier preferred or last chosen entries and nuke them
5713        findPreferredActivity(intent, resolvedType,
5714                flags, query, 0, false, true, false, userId);
5715        // Add the new activity as the last chosen for this filter
5716        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5717                "Setting last chosen");
5718    }
5719
5720    @Override
5721    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5722        final int userId = UserHandle.getCallingUserId();
5723        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5724        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5725                userId);
5726        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5727                false, false, false, userId);
5728    }
5729
5730    /**
5731     * Returns whether or not instant apps have been disabled remotely.
5732     */
5733    private boolean isEphemeralDisabled() {
5734        return mEphemeralAppsDisabled;
5735    }
5736
5737    private boolean isEphemeralAllowed(
5738            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5739            boolean skipPackageCheck) {
5740        final int callingUser = UserHandle.getCallingUserId();
5741        if (mInstantAppResolverConnection == null) {
5742            return false;
5743        }
5744        if (mInstantAppInstallerActivity == null) {
5745            return false;
5746        }
5747        if (intent.getComponent() != null) {
5748            return false;
5749        }
5750        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5751            return false;
5752        }
5753        if (!skipPackageCheck && intent.getPackage() != null) {
5754            return false;
5755        }
5756        final boolean isWebUri = hasWebURI(intent);
5757        if (!isWebUri || intent.getData().getHost() == null) {
5758            return false;
5759        }
5760        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5761        // Or if there's already an ephemeral app installed that handles the action
5762        synchronized (mPackages) {
5763            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5764            for (int n = 0; n < count; n++) {
5765                final ResolveInfo info = resolvedActivities.get(n);
5766                final String packageName = info.activityInfo.packageName;
5767                final PackageSetting ps = mSettings.mPackages.get(packageName);
5768                if (ps != null) {
5769                    // only check domain verification status if the app is not a browser
5770                    if (!info.handleAllWebDataURI) {
5771                        // Try to get the status from User settings first
5772                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5773                        final int status = (int) (packedStatus >> 32);
5774                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5775                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5776                            if (DEBUG_EPHEMERAL) {
5777                                Slog.v(TAG, "DENY instant app;"
5778                                    + " pkg: " + packageName + ", status: " + status);
5779                            }
5780                            return false;
5781                        }
5782                    }
5783                    if (ps.getInstantApp(userId)) {
5784                        if (DEBUG_EPHEMERAL) {
5785                            Slog.v(TAG, "DENY instant app installed;"
5786                                    + " pkg: " + packageName);
5787                        }
5788                        return false;
5789                    }
5790                }
5791            }
5792        }
5793        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5794        return true;
5795    }
5796
5797    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5798            Intent origIntent, String resolvedType, String callingPackage,
5799            int userId) {
5800        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5801                new InstantAppRequest(responseObj, origIntent, resolvedType,
5802                        callingPackage, userId));
5803        mHandler.sendMessage(msg);
5804    }
5805
5806    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5807            int flags, List<ResolveInfo> query, int userId) {
5808        if (query != null) {
5809            final int N = query.size();
5810            if (N == 1) {
5811                return query.get(0);
5812            } else if (N > 1) {
5813                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5814                // If there is more than one activity with the same priority,
5815                // then let the user decide between them.
5816                ResolveInfo r0 = query.get(0);
5817                ResolveInfo r1 = query.get(1);
5818                if (DEBUG_INTENT_MATCHING || debug) {
5819                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5820                            + r1.activityInfo.name + "=" + r1.priority);
5821                }
5822                // If the first activity has a higher priority, or a different
5823                // default, then it is always desirable to pick it.
5824                if (r0.priority != r1.priority
5825                        || r0.preferredOrder != r1.preferredOrder
5826                        || r0.isDefault != r1.isDefault) {
5827                    return query.get(0);
5828                }
5829                // If we have saved a preference for a preferred activity for
5830                // this Intent, use that.
5831                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5832                        flags, query, r0.priority, true, false, debug, userId);
5833                if (ri != null) {
5834                    return ri;
5835                }
5836                // If we have an ephemeral app, use it
5837                for (int i = 0; i < N; i++) {
5838                    ri = query.get(i);
5839                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5840                        return ri;
5841                    }
5842                }
5843                ri = new ResolveInfo(mResolveInfo);
5844                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5845                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5846                // If all of the options come from the same package, show the application's
5847                // label and icon instead of the generic resolver's.
5848                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5849                // and then throw away the ResolveInfo itself, meaning that the caller loses
5850                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5851                // a fallback for this case; we only set the target package's resources on
5852                // the ResolveInfo, not the ActivityInfo.
5853                final String intentPackage = intent.getPackage();
5854                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5855                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5856                    ri.resolvePackageName = intentPackage;
5857                    if (userNeedsBadging(userId)) {
5858                        ri.noResourceId = true;
5859                    } else {
5860                        ri.icon = appi.icon;
5861                    }
5862                    ri.iconResourceId = appi.icon;
5863                    ri.labelRes = appi.labelRes;
5864                }
5865                ri.activityInfo.applicationInfo = new ApplicationInfo(
5866                        ri.activityInfo.applicationInfo);
5867                if (userId != 0) {
5868                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5869                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5870                }
5871                // Make sure that the resolver is displayable in car mode
5872                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5873                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5874                return ri;
5875            }
5876        }
5877        return null;
5878    }
5879
5880    /**
5881     * Return true if the given list is not empty and all of its contents have
5882     * an activityInfo with the given package name.
5883     */
5884    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5885        if (ArrayUtils.isEmpty(list)) {
5886            return false;
5887        }
5888        for (int i = 0, N = list.size(); i < N; i++) {
5889            final ResolveInfo ri = list.get(i);
5890            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5891            if (ai == null || !packageName.equals(ai.packageName)) {
5892                return false;
5893            }
5894        }
5895        return true;
5896    }
5897
5898    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5899            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5900        final int N = query.size();
5901        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5902                .get(userId);
5903        // Get the list of persistent preferred activities that handle the intent
5904        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5905        List<PersistentPreferredActivity> pprefs = ppir != null
5906                ? ppir.queryIntent(intent, resolvedType,
5907                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5908                        userId)
5909                : null;
5910        if (pprefs != null && pprefs.size() > 0) {
5911            final int M = pprefs.size();
5912            for (int i=0; i<M; i++) {
5913                final PersistentPreferredActivity ppa = pprefs.get(i);
5914                if (DEBUG_PREFERRED || debug) {
5915                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5916                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5917                            + "\n  component=" + ppa.mComponent);
5918                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5919                }
5920                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5921                        flags | MATCH_DISABLED_COMPONENTS, userId);
5922                if (DEBUG_PREFERRED || debug) {
5923                    Slog.v(TAG, "Found persistent preferred activity:");
5924                    if (ai != null) {
5925                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5926                    } else {
5927                        Slog.v(TAG, "  null");
5928                    }
5929                }
5930                if (ai == null) {
5931                    // This previously registered persistent preferred activity
5932                    // component is no longer known. Ignore it and do NOT remove it.
5933                    continue;
5934                }
5935                for (int j=0; j<N; j++) {
5936                    final ResolveInfo ri = query.get(j);
5937                    if (!ri.activityInfo.applicationInfo.packageName
5938                            .equals(ai.applicationInfo.packageName)) {
5939                        continue;
5940                    }
5941                    if (!ri.activityInfo.name.equals(ai.name)) {
5942                        continue;
5943                    }
5944                    //  Found a persistent preference that can handle the intent.
5945                    if (DEBUG_PREFERRED || debug) {
5946                        Slog.v(TAG, "Returning persistent preferred activity: " +
5947                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5948                    }
5949                    return ri;
5950                }
5951            }
5952        }
5953        return null;
5954    }
5955
5956    // TODO: handle preferred activities missing while user has amnesia
5957    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5958            List<ResolveInfo> query, int priority, boolean always,
5959            boolean removeMatches, boolean debug, int userId) {
5960        if (!sUserManager.exists(userId)) return null;
5961        final int callingUid = Binder.getCallingUid();
5962        flags = updateFlagsForResolve(
5963                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5964        intent = updateIntentForResolve(intent);
5965        // writer
5966        synchronized (mPackages) {
5967            // Try to find a matching persistent preferred activity.
5968            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5969                    debug, userId);
5970
5971            // If a persistent preferred activity matched, use it.
5972            if (pri != null) {
5973                return pri;
5974            }
5975
5976            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5977            // Get the list of preferred activities that handle the intent
5978            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5979            List<PreferredActivity> prefs = pir != null
5980                    ? pir.queryIntent(intent, resolvedType,
5981                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5982                            userId)
5983                    : null;
5984            if (prefs != null && prefs.size() > 0) {
5985                boolean changed = false;
5986                try {
5987                    // First figure out how good the original match set is.
5988                    // We will only allow preferred activities that came
5989                    // from the same match quality.
5990                    int match = 0;
5991
5992                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5993
5994                    final int N = query.size();
5995                    for (int j=0; j<N; j++) {
5996                        final ResolveInfo ri = query.get(j);
5997                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5998                                + ": 0x" + Integer.toHexString(match));
5999                        if (ri.match > match) {
6000                            match = ri.match;
6001                        }
6002                    }
6003
6004                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6005                            + Integer.toHexString(match));
6006
6007                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6008                    final int M = prefs.size();
6009                    for (int i=0; i<M; i++) {
6010                        final PreferredActivity pa = prefs.get(i);
6011                        if (DEBUG_PREFERRED || debug) {
6012                            Slog.v(TAG, "Checking PreferredActivity ds="
6013                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6014                                    + "\n  component=" + pa.mPref.mComponent);
6015                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6016                        }
6017                        if (pa.mPref.mMatch != match) {
6018                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6019                                    + Integer.toHexString(pa.mPref.mMatch));
6020                            continue;
6021                        }
6022                        // If it's not an "always" type preferred activity and that's what we're
6023                        // looking for, skip it.
6024                        if (always && !pa.mPref.mAlways) {
6025                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6026                            continue;
6027                        }
6028                        final ActivityInfo ai = getActivityInfo(
6029                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6030                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6031                                userId);
6032                        if (DEBUG_PREFERRED || debug) {
6033                            Slog.v(TAG, "Found preferred activity:");
6034                            if (ai != null) {
6035                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6036                            } else {
6037                                Slog.v(TAG, "  null");
6038                            }
6039                        }
6040                        if (ai == null) {
6041                            // This previously registered preferred activity
6042                            // component is no longer known.  Most likely an update
6043                            // to the app was installed and in the new version this
6044                            // component no longer exists.  Clean it up by removing
6045                            // it from the preferred activities list, and skip it.
6046                            Slog.w(TAG, "Removing dangling preferred activity: "
6047                                    + pa.mPref.mComponent);
6048                            pir.removeFilter(pa);
6049                            changed = true;
6050                            continue;
6051                        }
6052                        for (int j=0; j<N; j++) {
6053                            final ResolveInfo ri = query.get(j);
6054                            if (!ri.activityInfo.applicationInfo.packageName
6055                                    .equals(ai.applicationInfo.packageName)) {
6056                                continue;
6057                            }
6058                            if (!ri.activityInfo.name.equals(ai.name)) {
6059                                continue;
6060                            }
6061
6062                            if (removeMatches) {
6063                                pir.removeFilter(pa);
6064                                changed = true;
6065                                if (DEBUG_PREFERRED) {
6066                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6067                                }
6068                                break;
6069                            }
6070
6071                            // Okay we found a previously set preferred or last chosen app.
6072                            // If the result set is different from when this
6073                            // was created, we need to clear it and re-ask the
6074                            // user their preference, if we're looking for an "always" type entry.
6075                            if (always && !pa.mPref.sameSet(query)) {
6076                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6077                                        + intent + " type " + resolvedType);
6078                                if (DEBUG_PREFERRED) {
6079                                    Slog.v(TAG, "Removing preferred activity since set changed "
6080                                            + pa.mPref.mComponent);
6081                                }
6082                                pir.removeFilter(pa);
6083                                // Re-add the filter as a "last chosen" entry (!always)
6084                                PreferredActivity lastChosen = new PreferredActivity(
6085                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6086                                pir.addFilter(lastChosen);
6087                                changed = true;
6088                                return null;
6089                            }
6090
6091                            // Yay! Either the set matched or we're looking for the last chosen
6092                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6093                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6094                            return ri;
6095                        }
6096                    }
6097                } finally {
6098                    if (changed) {
6099                        if (DEBUG_PREFERRED) {
6100                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6101                        }
6102                        scheduleWritePackageRestrictionsLocked(userId);
6103                    }
6104                }
6105            }
6106        }
6107        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6108        return null;
6109    }
6110
6111    /*
6112     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6113     */
6114    @Override
6115    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6116            int targetUserId) {
6117        mContext.enforceCallingOrSelfPermission(
6118                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6119        List<CrossProfileIntentFilter> matches =
6120                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6121        if (matches != null) {
6122            int size = matches.size();
6123            for (int i = 0; i < size; i++) {
6124                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6125            }
6126        }
6127        if (hasWebURI(intent)) {
6128            // cross-profile app linking works only towards the parent.
6129            final int callingUid = Binder.getCallingUid();
6130            final UserInfo parent = getProfileParent(sourceUserId);
6131            synchronized(mPackages) {
6132                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6133                        false /*includeInstantApps*/);
6134                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6135                        intent, resolvedType, flags, sourceUserId, parent.id);
6136                return xpDomainInfo != null;
6137            }
6138        }
6139        return false;
6140    }
6141
6142    private UserInfo getProfileParent(int userId) {
6143        final long identity = Binder.clearCallingIdentity();
6144        try {
6145            return sUserManager.getProfileParent(userId);
6146        } finally {
6147            Binder.restoreCallingIdentity(identity);
6148        }
6149    }
6150
6151    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6152            String resolvedType, int userId) {
6153        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6154        if (resolver != null) {
6155            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6156        }
6157        return null;
6158    }
6159
6160    @Override
6161    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6162            String resolvedType, int flags, int userId) {
6163        try {
6164            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6165
6166            return new ParceledListSlice<>(
6167                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6168        } finally {
6169            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6170        }
6171    }
6172
6173    /**
6174     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6175     * instant, returns {@code null}.
6176     */
6177    private String getInstantAppPackageName(int callingUid) {
6178        // If the caller is an isolated app use the owner's uid for the lookup.
6179        if (Process.isIsolated(callingUid)) {
6180            callingUid = mIsolatedOwners.get(callingUid);
6181        }
6182        final int appId = UserHandle.getAppId(callingUid);
6183        synchronized (mPackages) {
6184            final Object obj = mSettings.getUserIdLPr(appId);
6185            if (obj instanceof PackageSetting) {
6186                final PackageSetting ps = (PackageSetting) obj;
6187                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6188                return isInstantApp ? ps.pkg.packageName : null;
6189            }
6190        }
6191        return null;
6192    }
6193
6194    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6195            String resolvedType, int flags, int userId) {
6196        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6197    }
6198
6199    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6200            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6201        if (!sUserManager.exists(userId)) return Collections.emptyList();
6202        final int callingUid = Binder.getCallingUid();
6203        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6204        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6205        enforceCrossUserPermission(callingUid, userId,
6206                false /* requireFullPermission */, false /* checkShell */,
6207                "query intent activities");
6208        ComponentName comp = intent.getComponent();
6209        if (comp == null) {
6210            if (intent.getSelector() != null) {
6211                intent = intent.getSelector();
6212                comp = intent.getComponent();
6213            }
6214        }
6215
6216        if (comp != null) {
6217            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6218            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6219            if (ai != null) {
6220                // When specifying an explicit component, we prevent the activity from being
6221                // used when either 1) the calling package is normal and the activity is within
6222                // an ephemeral application or 2) the calling package is ephemeral and the
6223                // activity is not visible to ephemeral applications.
6224                final boolean matchInstantApp =
6225                        (flags & PackageManager.MATCH_INSTANT) != 0;
6226                final boolean matchVisibleToInstantAppOnly =
6227                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6228                final boolean isCallerInstantApp =
6229                        instantAppPkgName != null;
6230                final boolean isTargetSameInstantApp =
6231                        comp.getPackageName().equals(instantAppPkgName);
6232                final boolean isTargetInstantApp =
6233                        (ai.applicationInfo.privateFlags
6234                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6235                final boolean isTargetHiddenFromInstantApp =
6236                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6237                final boolean blockResolution =
6238                        !isTargetSameInstantApp
6239                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6240                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6241                                        && isTargetHiddenFromInstantApp));
6242                if (!blockResolution) {
6243                    final ResolveInfo ri = new ResolveInfo();
6244                    ri.activityInfo = ai;
6245                    list.add(ri);
6246                }
6247            }
6248            return applyPostResolutionFilter(list, instantAppPkgName);
6249        }
6250
6251        // reader
6252        boolean sortResult = false;
6253        boolean addEphemeral = false;
6254        List<ResolveInfo> result;
6255        final String pkgName = intent.getPackage();
6256        final boolean ephemeralDisabled = isEphemeralDisabled();
6257        synchronized (mPackages) {
6258            if (pkgName == null) {
6259                List<CrossProfileIntentFilter> matchingFilters =
6260                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6261                // Check for results that need to skip the current profile.
6262                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6263                        resolvedType, flags, userId);
6264                if (xpResolveInfo != null) {
6265                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6266                    xpResult.add(xpResolveInfo);
6267                    return applyPostResolutionFilter(
6268                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6269                }
6270
6271                // Check for results in the current profile.
6272                result = filterIfNotSystemUser(mActivities.queryIntent(
6273                        intent, resolvedType, flags, userId), userId);
6274                addEphemeral = !ephemeralDisabled
6275                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6276                // Check for cross profile results.
6277                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6278                xpResolveInfo = queryCrossProfileIntents(
6279                        matchingFilters, intent, resolvedType, flags, userId,
6280                        hasNonNegativePriorityResult);
6281                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6282                    boolean isVisibleToUser = filterIfNotSystemUser(
6283                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6284                    if (isVisibleToUser) {
6285                        result.add(xpResolveInfo);
6286                        sortResult = true;
6287                    }
6288                }
6289                if (hasWebURI(intent)) {
6290                    CrossProfileDomainInfo xpDomainInfo = null;
6291                    final UserInfo parent = getProfileParent(userId);
6292                    if (parent != null) {
6293                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6294                                flags, userId, parent.id);
6295                    }
6296                    if (xpDomainInfo != null) {
6297                        if (xpResolveInfo != null) {
6298                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6299                            // in the result.
6300                            result.remove(xpResolveInfo);
6301                        }
6302                        if (result.size() == 0 && !addEphemeral) {
6303                            // No result in current profile, but found candidate in parent user.
6304                            // And we are not going to add emphemeral app, so we can return the
6305                            // result straight away.
6306                            result.add(xpDomainInfo.resolveInfo);
6307                            return applyPostResolutionFilter(result, instantAppPkgName);
6308                        }
6309                    } else if (result.size() <= 1 && !addEphemeral) {
6310                        // No result in parent user and <= 1 result in current profile, and we
6311                        // are not going to add emphemeral app, so we can return the result without
6312                        // further processing.
6313                        return applyPostResolutionFilter(result, instantAppPkgName);
6314                    }
6315                    // We have more than one candidate (combining results from current and parent
6316                    // profile), so we need filtering and sorting.
6317                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6318                            intent, flags, result, xpDomainInfo, userId);
6319                    sortResult = true;
6320                }
6321            } else {
6322                final PackageParser.Package pkg = mPackages.get(pkgName);
6323                if (pkg != null) {
6324                    return applyPostResolutionFilter(filterIfNotSystemUser(
6325                            mActivities.queryIntentForPackage(
6326                                    intent, resolvedType, flags, pkg.activities, userId),
6327                            userId), instantAppPkgName);
6328                } else {
6329                    // the caller wants to resolve for a particular package; however, there
6330                    // were no installed results, so, try to find an ephemeral result
6331                    addEphemeral = !ephemeralDisabled
6332                            && isEphemeralAllowed(
6333                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6334                    result = new ArrayList<ResolveInfo>();
6335                }
6336            }
6337        }
6338        if (addEphemeral) {
6339            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6340            final InstantAppRequest requestObject = new InstantAppRequest(
6341                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6342                    null /*callingPackage*/, userId);
6343            final AuxiliaryResolveInfo auxiliaryResponse =
6344                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6345                            mContext, mInstantAppResolverConnection, requestObject);
6346            if (auxiliaryResponse != null) {
6347                if (DEBUG_EPHEMERAL) {
6348                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6349                }
6350                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6351                final PackageSetting ps =
6352                        mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6353                if (ps != null) {
6354                    ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6355                            mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6356                    ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6357                    ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6358                    // make sure this resolver is the default
6359                    ephemeralInstaller.isDefault = true;
6360                    ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6361                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6362                    // add a non-generic filter
6363                    ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6364                    ephemeralInstaller.filter.addDataPath(
6365                            intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6366                    ephemeralInstaller.instantAppAvailable = true;
6367                    result.add(ephemeralInstaller);
6368                }
6369            }
6370            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6371        }
6372        if (sortResult) {
6373            Collections.sort(result, mResolvePrioritySorter);
6374        }
6375        return applyPostResolutionFilter(result, instantAppPkgName);
6376    }
6377
6378    private static class CrossProfileDomainInfo {
6379        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6380        ResolveInfo resolveInfo;
6381        /* Best domain verification status of the activities found in the other profile */
6382        int bestDomainVerificationStatus;
6383    }
6384
6385    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6386            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6387        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6388                sourceUserId)) {
6389            return null;
6390        }
6391        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6392                resolvedType, flags, parentUserId);
6393
6394        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6395            return null;
6396        }
6397        CrossProfileDomainInfo result = null;
6398        int size = resultTargetUser.size();
6399        for (int i = 0; i < size; i++) {
6400            ResolveInfo riTargetUser = resultTargetUser.get(i);
6401            // Intent filter verification is only for filters that specify a host. So don't return
6402            // those that handle all web uris.
6403            if (riTargetUser.handleAllWebDataURI) {
6404                continue;
6405            }
6406            String packageName = riTargetUser.activityInfo.packageName;
6407            PackageSetting ps = mSettings.mPackages.get(packageName);
6408            if (ps == null) {
6409                continue;
6410            }
6411            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6412            int status = (int)(verificationState >> 32);
6413            if (result == null) {
6414                result = new CrossProfileDomainInfo();
6415                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6416                        sourceUserId, parentUserId);
6417                result.bestDomainVerificationStatus = status;
6418            } else {
6419                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6420                        result.bestDomainVerificationStatus);
6421            }
6422        }
6423        // Don't consider matches with status NEVER across profiles.
6424        if (result != null && result.bestDomainVerificationStatus
6425                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6426            return null;
6427        }
6428        return result;
6429    }
6430
6431    /**
6432     * Verification statuses are ordered from the worse to the best, except for
6433     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6434     */
6435    private int bestDomainVerificationStatus(int status1, int status2) {
6436        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6437            return status2;
6438        }
6439        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6440            return status1;
6441        }
6442        return (int) MathUtils.max(status1, status2);
6443    }
6444
6445    private boolean isUserEnabled(int userId) {
6446        long callingId = Binder.clearCallingIdentity();
6447        try {
6448            UserInfo userInfo = sUserManager.getUserInfo(userId);
6449            return userInfo != null && userInfo.isEnabled();
6450        } finally {
6451            Binder.restoreCallingIdentity(callingId);
6452        }
6453    }
6454
6455    /**
6456     * Filter out activities with systemUserOnly flag set, when current user is not System.
6457     *
6458     * @return filtered list
6459     */
6460    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6461        if (userId == UserHandle.USER_SYSTEM) {
6462            return resolveInfos;
6463        }
6464        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6465            ResolveInfo info = resolveInfos.get(i);
6466            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6467                resolveInfos.remove(i);
6468            }
6469        }
6470        return resolveInfos;
6471    }
6472
6473    /**
6474     * Filters out ephemeral activities.
6475     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6476     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6477     *
6478     * @param resolveInfos The pre-filtered list of resolved activities
6479     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6480     *          is performed.
6481     * @return A filtered list of resolved activities.
6482     */
6483    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6484            String ephemeralPkgName) {
6485        // TODO: When adding on-demand split support for non-instant apps, remove this check
6486        // and always apply post filtering
6487        if (ephemeralPkgName == null) {
6488            return resolveInfos;
6489        }
6490        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6491            final ResolveInfo info = resolveInfos.get(i);
6492            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6493            // allow activities that are defined in the provided package
6494            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6495                if (info.activityInfo.splitName != null
6496                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6497                                info.activityInfo.splitName)) {
6498                    // requested activity is defined in a split that hasn't been installed yet.
6499                    // add the installer to the resolve list
6500                    if (DEBUG_EPHEMERAL) {
6501                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6502                    }
6503                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6504                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6505                            info.activityInfo.packageName, info.activityInfo.splitName,
6506                            info.activityInfo.applicationInfo.versionCode);
6507                    // make sure this resolver is the default
6508                    installerInfo.isDefault = true;
6509                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6510                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6511                    // add a non-generic filter
6512                    installerInfo.filter = new IntentFilter();
6513                    // load resources from the correct package
6514                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6515                    resolveInfos.set(i, installerInfo);
6516                }
6517                continue;
6518            }
6519            // allow activities that have been explicitly exposed to ephemeral apps
6520            if (!isEphemeralApp
6521                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6522                continue;
6523            }
6524            resolveInfos.remove(i);
6525        }
6526        return resolveInfos;
6527    }
6528
6529    /**
6530     * @param resolveInfos list of resolve infos in descending priority order
6531     * @return if the list contains a resolve info with non-negative priority
6532     */
6533    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6534        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6535    }
6536
6537    private static boolean hasWebURI(Intent intent) {
6538        if (intent.getData() == null) {
6539            return false;
6540        }
6541        final String scheme = intent.getScheme();
6542        if (TextUtils.isEmpty(scheme)) {
6543            return false;
6544        }
6545        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6546    }
6547
6548    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6549            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6550            int userId) {
6551        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6552
6553        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6554            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6555                    candidates.size());
6556        }
6557
6558        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6559        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6560        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6561        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6562        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6563        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6564
6565        synchronized (mPackages) {
6566            final int count = candidates.size();
6567            // First, try to use linked apps. Partition the candidates into four lists:
6568            // one for the final results, one for the "do not use ever", one for "undefined status"
6569            // and finally one for "browser app type".
6570            for (int n=0; n<count; n++) {
6571                ResolveInfo info = candidates.get(n);
6572                String packageName = info.activityInfo.packageName;
6573                PackageSetting ps = mSettings.mPackages.get(packageName);
6574                if (ps != null) {
6575                    // Add to the special match all list (Browser use case)
6576                    if (info.handleAllWebDataURI) {
6577                        matchAllList.add(info);
6578                        continue;
6579                    }
6580                    // Try to get the status from User settings first
6581                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6582                    int status = (int)(packedStatus >> 32);
6583                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6584                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6585                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6586                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6587                                    + " : linkgen=" + linkGeneration);
6588                        }
6589                        // Use link-enabled generation as preferredOrder, i.e.
6590                        // prefer newly-enabled over earlier-enabled.
6591                        info.preferredOrder = linkGeneration;
6592                        alwaysList.add(info);
6593                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6594                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6595                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6596                        }
6597                        neverList.add(info);
6598                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6599                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6600                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6601                        }
6602                        alwaysAskList.add(info);
6603                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6604                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6605                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6606                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6607                        }
6608                        undefinedList.add(info);
6609                    }
6610                }
6611            }
6612
6613            // We'll want to include browser possibilities in a few cases
6614            boolean includeBrowser = false;
6615
6616            // First try to add the "always" resolution(s) for the current user, if any
6617            if (alwaysList.size() > 0) {
6618                result.addAll(alwaysList);
6619            } else {
6620                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6621                result.addAll(undefinedList);
6622                // Maybe add one for the other profile.
6623                if (xpDomainInfo != null && (
6624                        xpDomainInfo.bestDomainVerificationStatus
6625                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6626                    result.add(xpDomainInfo.resolveInfo);
6627                }
6628                includeBrowser = true;
6629            }
6630
6631            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6632            // If there were 'always' entries their preferred order has been set, so we also
6633            // back that off to make the alternatives equivalent
6634            if (alwaysAskList.size() > 0) {
6635                for (ResolveInfo i : result) {
6636                    i.preferredOrder = 0;
6637                }
6638                result.addAll(alwaysAskList);
6639                includeBrowser = true;
6640            }
6641
6642            if (includeBrowser) {
6643                // Also add browsers (all of them or only the default one)
6644                if (DEBUG_DOMAIN_VERIFICATION) {
6645                    Slog.v(TAG, "   ...including browsers in candidate set");
6646                }
6647                if ((matchFlags & MATCH_ALL) != 0) {
6648                    result.addAll(matchAllList);
6649                } else {
6650                    // Browser/generic handling case.  If there's a default browser, go straight
6651                    // to that (but only if there is no other higher-priority match).
6652                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6653                    int maxMatchPrio = 0;
6654                    ResolveInfo defaultBrowserMatch = null;
6655                    final int numCandidates = matchAllList.size();
6656                    for (int n = 0; n < numCandidates; n++) {
6657                        ResolveInfo info = matchAllList.get(n);
6658                        // track the highest overall match priority...
6659                        if (info.priority > maxMatchPrio) {
6660                            maxMatchPrio = info.priority;
6661                        }
6662                        // ...and the highest-priority default browser match
6663                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6664                            if (defaultBrowserMatch == null
6665                                    || (defaultBrowserMatch.priority < info.priority)) {
6666                                if (debug) {
6667                                    Slog.v(TAG, "Considering default browser match " + info);
6668                                }
6669                                defaultBrowserMatch = info;
6670                            }
6671                        }
6672                    }
6673                    if (defaultBrowserMatch != null
6674                            && defaultBrowserMatch.priority >= maxMatchPrio
6675                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6676                    {
6677                        if (debug) {
6678                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6679                        }
6680                        result.add(defaultBrowserMatch);
6681                    } else {
6682                        result.addAll(matchAllList);
6683                    }
6684                }
6685
6686                // If there is nothing selected, add all candidates and remove the ones that the user
6687                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6688                if (result.size() == 0) {
6689                    result.addAll(candidates);
6690                    result.removeAll(neverList);
6691                }
6692            }
6693        }
6694        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6695            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6696                    result.size());
6697            for (ResolveInfo info : result) {
6698                Slog.v(TAG, "  + " + info.activityInfo);
6699            }
6700        }
6701        return result;
6702    }
6703
6704    // Returns a packed value as a long:
6705    //
6706    // high 'int'-sized word: link status: undefined/ask/never/always.
6707    // low 'int'-sized word: relative priority among 'always' results.
6708    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6709        long result = ps.getDomainVerificationStatusForUser(userId);
6710        // if none available, get the master status
6711        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6712            if (ps.getIntentFilterVerificationInfo() != null) {
6713                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6714            }
6715        }
6716        return result;
6717    }
6718
6719    private ResolveInfo querySkipCurrentProfileIntents(
6720            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6721            int flags, int sourceUserId) {
6722        if (matchingFilters != null) {
6723            int size = matchingFilters.size();
6724            for (int i = 0; i < size; i ++) {
6725                CrossProfileIntentFilter filter = matchingFilters.get(i);
6726                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6727                    // Checking if there are activities in the target user that can handle the
6728                    // intent.
6729                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6730                            resolvedType, flags, sourceUserId);
6731                    if (resolveInfo != null) {
6732                        return resolveInfo;
6733                    }
6734                }
6735            }
6736        }
6737        return null;
6738    }
6739
6740    // Return matching ResolveInfo in target user if any.
6741    private ResolveInfo queryCrossProfileIntents(
6742            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6743            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6744        if (matchingFilters != null) {
6745            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6746            // match the same intent. For performance reasons, it is better not to
6747            // run queryIntent twice for the same userId
6748            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6749            int size = matchingFilters.size();
6750            for (int i = 0; i < size; i++) {
6751                CrossProfileIntentFilter filter = matchingFilters.get(i);
6752                int targetUserId = filter.getTargetUserId();
6753                boolean skipCurrentProfile =
6754                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6755                boolean skipCurrentProfileIfNoMatchFound =
6756                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6757                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6758                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6759                    // Checking if there are activities in the target user that can handle the
6760                    // intent.
6761                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6762                            resolvedType, flags, sourceUserId);
6763                    if (resolveInfo != null) return resolveInfo;
6764                    alreadyTriedUserIds.put(targetUserId, true);
6765                }
6766            }
6767        }
6768        return null;
6769    }
6770
6771    /**
6772     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6773     * will forward the intent to the filter's target user.
6774     * Otherwise, returns null.
6775     */
6776    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6777            String resolvedType, int flags, int sourceUserId) {
6778        int targetUserId = filter.getTargetUserId();
6779        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6780                resolvedType, flags, targetUserId);
6781        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6782            // If all the matches in the target profile are suspended, return null.
6783            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6784                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6785                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6786                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6787                            targetUserId);
6788                }
6789            }
6790        }
6791        return null;
6792    }
6793
6794    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6795            int sourceUserId, int targetUserId) {
6796        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6797        long ident = Binder.clearCallingIdentity();
6798        boolean targetIsProfile;
6799        try {
6800            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6801        } finally {
6802            Binder.restoreCallingIdentity(ident);
6803        }
6804        String className;
6805        if (targetIsProfile) {
6806            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6807        } else {
6808            className = FORWARD_INTENT_TO_PARENT;
6809        }
6810        ComponentName forwardingActivityComponentName = new ComponentName(
6811                mAndroidApplication.packageName, className);
6812        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6813                sourceUserId);
6814        if (!targetIsProfile) {
6815            forwardingActivityInfo.showUserIcon = targetUserId;
6816            forwardingResolveInfo.noResourceId = true;
6817        }
6818        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6819        forwardingResolveInfo.priority = 0;
6820        forwardingResolveInfo.preferredOrder = 0;
6821        forwardingResolveInfo.match = 0;
6822        forwardingResolveInfo.isDefault = true;
6823        forwardingResolveInfo.filter = filter;
6824        forwardingResolveInfo.targetUserId = targetUserId;
6825        return forwardingResolveInfo;
6826    }
6827
6828    @Override
6829    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6830            Intent[] specifics, String[] specificTypes, Intent intent,
6831            String resolvedType, int flags, int userId) {
6832        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6833                specificTypes, intent, resolvedType, flags, userId));
6834    }
6835
6836    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6837            Intent[] specifics, String[] specificTypes, Intent intent,
6838            String resolvedType, int flags, int userId) {
6839        if (!sUserManager.exists(userId)) return Collections.emptyList();
6840        final int callingUid = Binder.getCallingUid();
6841        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6842                false /*includeInstantApps*/);
6843        enforceCrossUserPermission(callingUid, userId,
6844                false /*requireFullPermission*/, false /*checkShell*/,
6845                "query intent activity options");
6846        final String resultsAction = intent.getAction();
6847
6848        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6849                | PackageManager.GET_RESOLVED_FILTER, userId);
6850
6851        if (DEBUG_INTENT_MATCHING) {
6852            Log.v(TAG, "Query " + intent + ": " + results);
6853        }
6854
6855        int specificsPos = 0;
6856        int N;
6857
6858        // todo: note that the algorithm used here is O(N^2).  This
6859        // isn't a problem in our current environment, but if we start running
6860        // into situations where we have more than 5 or 10 matches then this
6861        // should probably be changed to something smarter...
6862
6863        // First we go through and resolve each of the specific items
6864        // that were supplied, taking care of removing any corresponding
6865        // duplicate items in the generic resolve list.
6866        if (specifics != null) {
6867            for (int i=0; i<specifics.length; i++) {
6868                final Intent sintent = specifics[i];
6869                if (sintent == null) {
6870                    continue;
6871                }
6872
6873                if (DEBUG_INTENT_MATCHING) {
6874                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6875                }
6876
6877                String action = sintent.getAction();
6878                if (resultsAction != null && resultsAction.equals(action)) {
6879                    // If this action was explicitly requested, then don't
6880                    // remove things that have it.
6881                    action = null;
6882                }
6883
6884                ResolveInfo ri = null;
6885                ActivityInfo ai = null;
6886
6887                ComponentName comp = sintent.getComponent();
6888                if (comp == null) {
6889                    ri = resolveIntent(
6890                        sintent,
6891                        specificTypes != null ? specificTypes[i] : null,
6892                            flags, userId);
6893                    if (ri == null) {
6894                        continue;
6895                    }
6896                    if (ri == mResolveInfo) {
6897                        // ACK!  Must do something better with this.
6898                    }
6899                    ai = ri.activityInfo;
6900                    comp = new ComponentName(ai.applicationInfo.packageName,
6901                            ai.name);
6902                } else {
6903                    ai = getActivityInfo(comp, flags, userId);
6904                    if (ai == null) {
6905                        continue;
6906                    }
6907                }
6908
6909                // Look for any generic query activities that are duplicates
6910                // of this specific one, and remove them from the results.
6911                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6912                N = results.size();
6913                int j;
6914                for (j=specificsPos; j<N; j++) {
6915                    ResolveInfo sri = results.get(j);
6916                    if ((sri.activityInfo.name.equals(comp.getClassName())
6917                            && sri.activityInfo.applicationInfo.packageName.equals(
6918                                    comp.getPackageName()))
6919                        || (action != null && sri.filter.matchAction(action))) {
6920                        results.remove(j);
6921                        if (DEBUG_INTENT_MATCHING) Log.v(
6922                            TAG, "Removing duplicate item from " + j
6923                            + " due to specific " + specificsPos);
6924                        if (ri == null) {
6925                            ri = sri;
6926                        }
6927                        j--;
6928                        N--;
6929                    }
6930                }
6931
6932                // Add this specific item to its proper place.
6933                if (ri == null) {
6934                    ri = new ResolveInfo();
6935                    ri.activityInfo = ai;
6936                }
6937                results.add(specificsPos, ri);
6938                ri.specificIndex = i;
6939                specificsPos++;
6940            }
6941        }
6942
6943        // Now we go through the remaining generic results and remove any
6944        // duplicate actions that are found here.
6945        N = results.size();
6946        for (int i=specificsPos; i<N-1; i++) {
6947            final ResolveInfo rii = results.get(i);
6948            if (rii.filter == null) {
6949                continue;
6950            }
6951
6952            // Iterate over all of the actions of this result's intent
6953            // filter...  typically this should be just one.
6954            final Iterator<String> it = rii.filter.actionsIterator();
6955            if (it == null) {
6956                continue;
6957            }
6958            while (it.hasNext()) {
6959                final String action = it.next();
6960                if (resultsAction != null && resultsAction.equals(action)) {
6961                    // If this action was explicitly requested, then don't
6962                    // remove things that have it.
6963                    continue;
6964                }
6965                for (int j=i+1; j<N; j++) {
6966                    final ResolveInfo rij = results.get(j);
6967                    if (rij.filter != null && rij.filter.hasAction(action)) {
6968                        results.remove(j);
6969                        if (DEBUG_INTENT_MATCHING) Log.v(
6970                            TAG, "Removing duplicate item from " + j
6971                            + " due to action " + action + " at " + i);
6972                        j--;
6973                        N--;
6974                    }
6975                }
6976            }
6977
6978            // If the caller didn't request filter information, drop it now
6979            // so we don't have to marshall/unmarshall it.
6980            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6981                rii.filter = null;
6982            }
6983        }
6984
6985        // Filter out the caller activity if so requested.
6986        if (caller != null) {
6987            N = results.size();
6988            for (int i=0; i<N; i++) {
6989                ActivityInfo ainfo = results.get(i).activityInfo;
6990                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6991                        && caller.getClassName().equals(ainfo.name)) {
6992                    results.remove(i);
6993                    break;
6994                }
6995            }
6996        }
6997
6998        // If the caller didn't request filter information,
6999        // drop them now so we don't have to
7000        // marshall/unmarshall it.
7001        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7002            N = results.size();
7003            for (int i=0; i<N; i++) {
7004                results.get(i).filter = null;
7005            }
7006        }
7007
7008        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7009        return results;
7010    }
7011
7012    @Override
7013    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7014            String resolvedType, int flags, int userId) {
7015        return new ParceledListSlice<>(
7016                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7017    }
7018
7019    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7020            String resolvedType, int flags, int userId) {
7021        if (!sUserManager.exists(userId)) return Collections.emptyList();
7022        final int callingUid = Binder.getCallingUid();
7023        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7024                false /*includeInstantApps*/);
7025        ComponentName comp = intent.getComponent();
7026        if (comp == null) {
7027            if (intent.getSelector() != null) {
7028                intent = intent.getSelector();
7029                comp = intent.getComponent();
7030            }
7031        }
7032        if (comp != null) {
7033            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7034            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7035            if (ai != null) {
7036                ResolveInfo ri = new ResolveInfo();
7037                ri.activityInfo = ai;
7038                list.add(ri);
7039            }
7040            return list;
7041        }
7042
7043        // reader
7044        synchronized (mPackages) {
7045            String pkgName = intent.getPackage();
7046            if (pkgName == null) {
7047                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7048            }
7049            final PackageParser.Package pkg = mPackages.get(pkgName);
7050            if (pkg != null) {
7051                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7052                        userId);
7053            }
7054            return Collections.emptyList();
7055        }
7056    }
7057
7058    @Override
7059    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7060        final int callingUid = Binder.getCallingUid();
7061        return resolveServiceInternal(
7062                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7063    }
7064
7065    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7066            int userId, int callingUid, boolean includeInstantApps) {
7067        if (!sUserManager.exists(userId)) return null;
7068        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7069        List<ResolveInfo> query = queryIntentServicesInternal(
7070                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7071        if (query != null) {
7072            if (query.size() >= 1) {
7073                // If there is more than one service with the same priority,
7074                // just arbitrarily pick the first one.
7075                return query.get(0);
7076            }
7077        }
7078        return null;
7079    }
7080
7081    @Override
7082    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7083            String resolvedType, int flags, int userId) {
7084        final int callingUid = Binder.getCallingUid();
7085        return new ParceledListSlice<>(queryIntentServicesInternal(
7086                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7087    }
7088
7089    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7090            String resolvedType, int flags, int userId, int callingUid,
7091            boolean includeInstantApps) {
7092        if (!sUserManager.exists(userId)) return Collections.emptyList();
7093        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7094        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7095        ComponentName comp = intent.getComponent();
7096        if (comp == null) {
7097            if (intent.getSelector() != null) {
7098                intent = intent.getSelector();
7099                comp = intent.getComponent();
7100            }
7101        }
7102        if (comp != null) {
7103            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7104            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7105            if (si != null) {
7106                // When specifying an explicit component, we prevent the service from being
7107                // used when either 1) the service is in an instant application and the
7108                // caller is not the same instant application or 2) the calling package is
7109                // ephemeral and the activity is not visible to ephemeral applications.
7110                final boolean matchInstantApp =
7111                        (flags & PackageManager.MATCH_INSTANT) != 0;
7112                final boolean matchVisibleToInstantAppOnly =
7113                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7114                final boolean isCallerInstantApp =
7115                        instantAppPkgName != null;
7116                final boolean isTargetSameInstantApp =
7117                        comp.getPackageName().equals(instantAppPkgName);
7118                final boolean isTargetInstantApp =
7119                        (si.applicationInfo.privateFlags
7120                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7121                final boolean isTargetHiddenFromInstantApp =
7122                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7123                final boolean blockResolution =
7124                        !isTargetSameInstantApp
7125                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7126                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7127                                        && isTargetHiddenFromInstantApp));
7128                if (!blockResolution) {
7129                    final ResolveInfo ri = new ResolveInfo();
7130                    ri.serviceInfo = si;
7131                    list.add(ri);
7132                }
7133            }
7134            return list;
7135        }
7136
7137        // reader
7138        synchronized (mPackages) {
7139            String pkgName = intent.getPackage();
7140            if (pkgName == null) {
7141                return applyPostServiceResolutionFilter(
7142                        mServices.queryIntent(intent, resolvedType, flags, userId),
7143                        instantAppPkgName);
7144            }
7145            final PackageParser.Package pkg = mPackages.get(pkgName);
7146            if (pkg != null) {
7147                return applyPostServiceResolutionFilter(
7148                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7149                                userId),
7150                        instantAppPkgName);
7151            }
7152            return Collections.emptyList();
7153        }
7154    }
7155
7156    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7157            String instantAppPkgName) {
7158        // TODO: When adding on-demand split support for non-instant apps, remove this check
7159        // and always apply post filtering
7160        if (instantAppPkgName == null) {
7161            return resolveInfos;
7162        }
7163        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7164            final ResolveInfo info = resolveInfos.get(i);
7165            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7166            // allow services that are defined in the provided package
7167            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7168                if (info.serviceInfo.splitName != null
7169                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7170                                info.serviceInfo.splitName)) {
7171                    // requested service is defined in a split that hasn't been installed yet.
7172                    // add the installer to the resolve list
7173                    if (DEBUG_EPHEMERAL) {
7174                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7175                    }
7176                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7177                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7178                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7179                            info.serviceInfo.applicationInfo.versionCode);
7180                    // make sure this resolver is the default
7181                    installerInfo.isDefault = true;
7182                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7183                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7184                    // add a non-generic filter
7185                    installerInfo.filter = new IntentFilter();
7186                    // load resources from the correct package
7187                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7188                    resolveInfos.set(i, installerInfo);
7189                }
7190                continue;
7191            }
7192            // allow services that have been explicitly exposed to ephemeral apps
7193            if (!isEphemeralApp
7194                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7195                continue;
7196            }
7197            resolveInfos.remove(i);
7198        }
7199        return resolveInfos;
7200    }
7201
7202    @Override
7203    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7204            String resolvedType, int flags, int userId) {
7205        return new ParceledListSlice<>(
7206                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7207    }
7208
7209    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7210            Intent intent, String resolvedType, int flags, int userId) {
7211        if (!sUserManager.exists(userId)) return Collections.emptyList();
7212        final int callingUid = Binder.getCallingUid();
7213        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7214        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7215                false /*includeInstantApps*/);
7216        ComponentName comp = intent.getComponent();
7217        if (comp == null) {
7218            if (intent.getSelector() != null) {
7219                intent = intent.getSelector();
7220                comp = intent.getComponent();
7221            }
7222        }
7223        if (comp != null) {
7224            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7225            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7226            if (pi != null) {
7227                // When specifying an explicit component, we prevent the provider from being
7228                // used when either 1) the provider is in an instant application and the
7229                // caller is not the same instant application or 2) the calling package is an
7230                // instant application and the provider is not visible to instant applications.
7231                final boolean matchInstantApp =
7232                        (flags & PackageManager.MATCH_INSTANT) != 0;
7233                final boolean matchVisibleToInstantAppOnly =
7234                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7235                final boolean isCallerInstantApp =
7236                        instantAppPkgName != null;
7237                final boolean isTargetSameInstantApp =
7238                        comp.getPackageName().equals(instantAppPkgName);
7239                final boolean isTargetInstantApp =
7240                        (pi.applicationInfo.privateFlags
7241                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7242                final boolean isTargetHiddenFromInstantApp =
7243                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7244                final boolean blockResolution =
7245                        !isTargetSameInstantApp
7246                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7247                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7248                                        && isTargetHiddenFromInstantApp));
7249                if (!blockResolution) {
7250                    final ResolveInfo ri = new ResolveInfo();
7251                    ri.providerInfo = pi;
7252                    list.add(ri);
7253                }
7254            }
7255            return list;
7256        }
7257
7258        // reader
7259        synchronized (mPackages) {
7260            String pkgName = intent.getPackage();
7261            if (pkgName == null) {
7262                return applyPostContentProviderResolutionFilter(
7263                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7264                        instantAppPkgName);
7265            }
7266            final PackageParser.Package pkg = mPackages.get(pkgName);
7267            if (pkg != null) {
7268                return applyPostContentProviderResolutionFilter(
7269                        mProviders.queryIntentForPackage(
7270                        intent, resolvedType, flags, pkg.providers, userId),
7271                        instantAppPkgName);
7272            }
7273            return Collections.emptyList();
7274        }
7275    }
7276
7277    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7278            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7279        // TODO: When adding on-demand split support for non-instant applications, remove
7280        // this check and always apply post filtering
7281        if (instantAppPkgName == null) {
7282            return resolveInfos;
7283        }
7284        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7285            final ResolveInfo info = resolveInfos.get(i);
7286            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7287            // allow providers that are defined in the provided package
7288            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7289                if (info.providerInfo.splitName != null
7290                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7291                                info.providerInfo.splitName)) {
7292                    // requested provider is defined in a split that hasn't been installed yet.
7293                    // add the installer to the resolve list
7294                    if (DEBUG_EPHEMERAL) {
7295                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7296                    }
7297                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7298                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7299                            info.providerInfo.packageName, info.providerInfo.splitName,
7300                            info.providerInfo.applicationInfo.versionCode);
7301                    // make sure this resolver is the default
7302                    installerInfo.isDefault = true;
7303                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7304                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7305                    // add a non-generic filter
7306                    installerInfo.filter = new IntentFilter();
7307                    // load resources from the correct package
7308                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7309                    resolveInfos.set(i, installerInfo);
7310                }
7311                continue;
7312            }
7313            // allow providers that have been explicitly exposed to instant applications
7314            if (!isEphemeralApp
7315                    && ((info.providerInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7316                continue;
7317            }
7318            resolveInfos.remove(i);
7319        }
7320        return resolveInfos;
7321    }
7322
7323    @Override
7324    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7325        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7326        flags = updateFlagsForPackage(flags, userId, null);
7327        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7328        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7329                true /* requireFullPermission */, false /* checkShell */,
7330                "get installed packages");
7331
7332        // writer
7333        synchronized (mPackages) {
7334            ArrayList<PackageInfo> list;
7335            if (listUninstalled) {
7336                list = new ArrayList<>(mSettings.mPackages.size());
7337                for (PackageSetting ps : mSettings.mPackages.values()) {
7338                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7339                        continue;
7340                    }
7341                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7342                    if (pi != null) {
7343                        list.add(pi);
7344                    }
7345                }
7346            } else {
7347                list = new ArrayList<>(mPackages.size());
7348                for (PackageParser.Package p : mPackages.values()) {
7349                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7350                            Binder.getCallingUid(), userId)) {
7351                        continue;
7352                    }
7353                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7354                            p.mExtras, flags, userId);
7355                    if (pi != null) {
7356                        list.add(pi);
7357                    }
7358                }
7359            }
7360
7361            return new ParceledListSlice<>(list);
7362        }
7363    }
7364
7365    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7366            String[] permissions, boolean[] tmp, int flags, int userId) {
7367        int numMatch = 0;
7368        final PermissionsState permissionsState = ps.getPermissionsState();
7369        for (int i=0; i<permissions.length; i++) {
7370            final String permission = permissions[i];
7371            if (permissionsState.hasPermission(permission, userId)) {
7372                tmp[i] = true;
7373                numMatch++;
7374            } else {
7375                tmp[i] = false;
7376            }
7377        }
7378        if (numMatch == 0) {
7379            return;
7380        }
7381        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7382
7383        // The above might return null in cases of uninstalled apps or install-state
7384        // skew across users/profiles.
7385        if (pi != null) {
7386            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7387                if (numMatch == permissions.length) {
7388                    pi.requestedPermissions = permissions;
7389                } else {
7390                    pi.requestedPermissions = new String[numMatch];
7391                    numMatch = 0;
7392                    for (int i=0; i<permissions.length; i++) {
7393                        if (tmp[i]) {
7394                            pi.requestedPermissions[numMatch] = permissions[i];
7395                            numMatch++;
7396                        }
7397                    }
7398                }
7399            }
7400            list.add(pi);
7401        }
7402    }
7403
7404    @Override
7405    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7406            String[] permissions, int flags, int userId) {
7407        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7408        flags = updateFlagsForPackage(flags, userId, permissions);
7409        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7410                true /* requireFullPermission */, false /* checkShell */,
7411                "get packages holding permissions");
7412        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7413
7414        // writer
7415        synchronized (mPackages) {
7416            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7417            boolean[] tmpBools = new boolean[permissions.length];
7418            if (listUninstalled) {
7419                for (PackageSetting ps : mSettings.mPackages.values()) {
7420                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7421                            userId);
7422                }
7423            } else {
7424                for (PackageParser.Package pkg : mPackages.values()) {
7425                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7426                    if (ps != null) {
7427                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7428                                userId);
7429                    }
7430                }
7431            }
7432
7433            return new ParceledListSlice<PackageInfo>(list);
7434        }
7435    }
7436
7437    @Override
7438    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7439        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7440        flags = updateFlagsForApplication(flags, userId, null);
7441        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7442
7443        // writer
7444        synchronized (mPackages) {
7445            ArrayList<ApplicationInfo> list;
7446            if (listUninstalled) {
7447                list = new ArrayList<>(mSettings.mPackages.size());
7448                for (PackageSetting ps : mSettings.mPackages.values()) {
7449                    ApplicationInfo ai;
7450                    int effectiveFlags = flags;
7451                    if (ps.isSystem()) {
7452                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7453                    }
7454                    if (ps.pkg != null) {
7455                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7456                            continue;
7457                        }
7458                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7459                                ps.readUserState(userId), userId);
7460                        if (ai != null) {
7461                            rebaseEnabledOverlays(ai, userId);
7462                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7463                        }
7464                    } else {
7465                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7466                        // and already converts to externally visible package name
7467                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7468                                Binder.getCallingUid(), effectiveFlags, userId);
7469                    }
7470                    if (ai != null) {
7471                        list.add(ai);
7472                    }
7473                }
7474            } else {
7475                list = new ArrayList<>(mPackages.size());
7476                for (PackageParser.Package p : mPackages.values()) {
7477                    if (p.mExtras != null) {
7478                        PackageSetting ps = (PackageSetting) p.mExtras;
7479                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7480                            continue;
7481                        }
7482                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7483                                ps.readUserState(userId), userId);
7484                        if (ai != null) {
7485                            rebaseEnabledOverlays(ai, userId);
7486                            ai.packageName = resolveExternalPackageNameLPr(p);
7487                            list.add(ai);
7488                        }
7489                    }
7490                }
7491            }
7492
7493            return new ParceledListSlice<>(list);
7494        }
7495    }
7496
7497    @Override
7498    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7499        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7500            return null;
7501        }
7502
7503        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7504                "getEphemeralApplications");
7505        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7506                true /* requireFullPermission */, false /* checkShell */,
7507                "getEphemeralApplications");
7508        synchronized (mPackages) {
7509            List<InstantAppInfo> instantApps = mInstantAppRegistry
7510                    .getInstantAppsLPr(userId);
7511            if (instantApps != null) {
7512                return new ParceledListSlice<>(instantApps);
7513            }
7514        }
7515        return null;
7516    }
7517
7518    @Override
7519    public boolean isInstantApp(String packageName, int userId) {
7520        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7521                true /* requireFullPermission */, false /* checkShell */,
7522                "isInstantApp");
7523        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7524            return false;
7525        }
7526        int uid = Binder.getCallingUid();
7527        if (Process.isIsolated(uid)) {
7528            uid = mIsolatedOwners.get(uid);
7529        }
7530
7531        synchronized (mPackages) {
7532            final PackageSetting ps = mSettings.mPackages.get(packageName);
7533            PackageParser.Package pkg = mPackages.get(packageName);
7534            final boolean returnAllowed =
7535                    ps != null
7536                    && (isCallerSameApp(packageName, uid)
7537                            || mContext.checkCallingOrSelfPermission(
7538                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7539                                            == PERMISSION_GRANTED
7540                            || mInstantAppRegistry.isInstantAccessGranted(
7541                                    userId, UserHandle.getAppId(uid), ps.appId));
7542            if (returnAllowed) {
7543                return ps.getInstantApp(userId);
7544            }
7545        }
7546        return false;
7547    }
7548
7549    @Override
7550    public byte[] getInstantAppCookie(String packageName, int userId) {
7551        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7552            return null;
7553        }
7554
7555        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7556                true /* requireFullPermission */, false /* checkShell */,
7557                "getInstantAppCookie");
7558        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7559            return null;
7560        }
7561        synchronized (mPackages) {
7562            return mInstantAppRegistry.getInstantAppCookieLPw(
7563                    packageName, userId);
7564        }
7565    }
7566
7567    @Override
7568    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7569        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7570            return true;
7571        }
7572
7573        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7574                true /* requireFullPermission */, true /* checkShell */,
7575                "setInstantAppCookie");
7576        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7577            return false;
7578        }
7579        synchronized (mPackages) {
7580            return mInstantAppRegistry.setInstantAppCookieLPw(
7581                    packageName, cookie, userId);
7582        }
7583    }
7584
7585    @Override
7586    public Bitmap getInstantAppIcon(String packageName, int userId) {
7587        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7588            return null;
7589        }
7590
7591        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7592                "getInstantAppIcon");
7593
7594        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7595                true /* requireFullPermission */, false /* checkShell */,
7596                "getInstantAppIcon");
7597
7598        synchronized (mPackages) {
7599            return mInstantAppRegistry.getInstantAppIconLPw(
7600                    packageName, userId);
7601        }
7602    }
7603
7604    private boolean isCallerSameApp(String packageName, int uid) {
7605        PackageParser.Package pkg = mPackages.get(packageName);
7606        return pkg != null
7607                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7608    }
7609
7610    @Override
7611    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7612        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7613    }
7614
7615    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7616        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7617
7618        // reader
7619        synchronized (mPackages) {
7620            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7621            final int userId = UserHandle.getCallingUserId();
7622            while (i.hasNext()) {
7623                final PackageParser.Package p = i.next();
7624                if (p.applicationInfo == null) continue;
7625
7626                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7627                        && !p.applicationInfo.isDirectBootAware();
7628                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7629                        && p.applicationInfo.isDirectBootAware();
7630
7631                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7632                        && (!mSafeMode || isSystemApp(p))
7633                        && (matchesUnaware || matchesAware)) {
7634                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7635                    if (ps != null) {
7636                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7637                                ps.readUserState(userId), userId);
7638                        if (ai != null) {
7639                            rebaseEnabledOverlays(ai, userId);
7640                            finalList.add(ai);
7641                        }
7642                    }
7643                }
7644            }
7645        }
7646
7647        return finalList;
7648    }
7649
7650    @Override
7651    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7652        if (!sUserManager.exists(userId)) return null;
7653        flags = updateFlagsForComponent(flags, userId, name);
7654        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7655        // reader
7656        synchronized (mPackages) {
7657            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7658            PackageSetting ps = provider != null
7659                    ? mSettings.mPackages.get(provider.owner.packageName)
7660                    : null;
7661            if (ps != null) {
7662                final boolean isInstantApp = ps.getInstantApp(userId);
7663                // normal application; filter out instant application provider
7664                if (instantAppPkgName == null && isInstantApp) {
7665                    return null;
7666                }
7667                // instant application; filter out other instant applications
7668                if (instantAppPkgName != null
7669                        && isInstantApp
7670                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7671                    return null;
7672                }
7673                // instant application; filter out non-exposed provider
7674                if (instantAppPkgName != null
7675                        && !isInstantApp
7676                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0) {
7677                    return null;
7678                }
7679                // provider not enabled
7680                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7681                    return null;
7682                }
7683                return PackageParser.generateProviderInfo(
7684                        provider, flags, ps.readUserState(userId), userId);
7685            }
7686            return null;
7687        }
7688    }
7689
7690    /**
7691     * @deprecated
7692     */
7693    @Deprecated
7694    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7695        // reader
7696        synchronized (mPackages) {
7697            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7698                    .entrySet().iterator();
7699            final int userId = UserHandle.getCallingUserId();
7700            while (i.hasNext()) {
7701                Map.Entry<String, PackageParser.Provider> entry = i.next();
7702                PackageParser.Provider p = entry.getValue();
7703                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7704
7705                if (ps != null && p.syncable
7706                        && (!mSafeMode || (p.info.applicationInfo.flags
7707                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7708                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7709                            ps.readUserState(userId), userId);
7710                    if (info != null) {
7711                        outNames.add(entry.getKey());
7712                        outInfo.add(info);
7713                    }
7714                }
7715            }
7716        }
7717    }
7718
7719    @Override
7720    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7721            int uid, int flags, String metaDataKey) {
7722        final int userId = processName != null ? UserHandle.getUserId(uid)
7723                : UserHandle.getCallingUserId();
7724        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7725        flags = updateFlagsForComponent(flags, userId, processName);
7726
7727        ArrayList<ProviderInfo> finalList = null;
7728        // reader
7729        synchronized (mPackages) {
7730            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7731            while (i.hasNext()) {
7732                final PackageParser.Provider p = i.next();
7733                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7734                if (ps != null && p.info.authority != null
7735                        && (processName == null
7736                                || (p.info.processName.equals(processName)
7737                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7738                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7739
7740                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7741                    // parameter.
7742                    if (metaDataKey != null
7743                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7744                        continue;
7745                    }
7746
7747                    if (finalList == null) {
7748                        finalList = new ArrayList<ProviderInfo>(3);
7749                    }
7750                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7751                            ps.readUserState(userId), userId);
7752                    if (info != null) {
7753                        finalList.add(info);
7754                    }
7755                }
7756            }
7757        }
7758
7759        if (finalList != null) {
7760            Collections.sort(finalList, mProviderInitOrderSorter);
7761            return new ParceledListSlice<ProviderInfo>(finalList);
7762        }
7763
7764        return ParceledListSlice.emptyList();
7765    }
7766
7767    @Override
7768    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7769        // reader
7770        synchronized (mPackages) {
7771            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7772            return PackageParser.generateInstrumentationInfo(i, flags);
7773        }
7774    }
7775
7776    @Override
7777    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7778            String targetPackage, int flags) {
7779        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7780    }
7781
7782    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7783            int flags) {
7784        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7785
7786        // reader
7787        synchronized (mPackages) {
7788            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7789            while (i.hasNext()) {
7790                final PackageParser.Instrumentation p = i.next();
7791                if (targetPackage == null
7792                        || targetPackage.equals(p.info.targetPackage)) {
7793                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7794                            flags);
7795                    if (ii != null) {
7796                        finalList.add(ii);
7797                    }
7798                }
7799            }
7800        }
7801
7802        return finalList;
7803    }
7804
7805    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7806        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7807        try {
7808            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7809        } finally {
7810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7811        }
7812    }
7813
7814    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7815        final File[] files = dir.listFiles();
7816        if (ArrayUtils.isEmpty(files)) {
7817            Log.d(TAG, "No files in app dir " + dir);
7818            return;
7819        }
7820
7821        if (DEBUG_PACKAGE_SCANNING) {
7822            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7823                    + " flags=0x" + Integer.toHexString(parseFlags));
7824        }
7825        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7826                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7827
7828        // Submit files for parsing in parallel
7829        int fileCount = 0;
7830        for (File file : files) {
7831            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7832                    && !PackageInstallerService.isStageName(file.getName());
7833            if (!isPackage) {
7834                // Ignore entries which are not packages
7835                continue;
7836            }
7837            parallelPackageParser.submit(file, parseFlags);
7838            fileCount++;
7839        }
7840
7841        // Process results one by one
7842        for (; fileCount > 0; fileCount--) {
7843            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7844            Throwable throwable = parseResult.throwable;
7845            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7846
7847            if (throwable == null) {
7848                // Static shared libraries have synthetic package names
7849                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7850                    renameStaticSharedLibraryPackage(parseResult.pkg);
7851                }
7852                try {
7853                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7854                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7855                                currentTime, null);
7856                    }
7857                } catch (PackageManagerException e) {
7858                    errorCode = e.error;
7859                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7860                }
7861            } else if (throwable instanceof PackageParser.PackageParserException) {
7862                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7863                        throwable;
7864                errorCode = e.error;
7865                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7866            } else {
7867                throw new IllegalStateException("Unexpected exception occurred while parsing "
7868                        + parseResult.scanFile, throwable);
7869            }
7870
7871            // Delete invalid userdata apps
7872            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7873                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7874                logCriticalInfo(Log.WARN,
7875                        "Deleting invalid package at " + parseResult.scanFile);
7876                removeCodePathLI(parseResult.scanFile);
7877            }
7878        }
7879        parallelPackageParser.close();
7880    }
7881
7882    private static File getSettingsProblemFile() {
7883        File dataDir = Environment.getDataDirectory();
7884        File systemDir = new File(dataDir, "system");
7885        File fname = new File(systemDir, "uiderrors.txt");
7886        return fname;
7887    }
7888
7889    static void reportSettingsProblem(int priority, String msg) {
7890        logCriticalInfo(priority, msg);
7891    }
7892
7893    public static void logCriticalInfo(int priority, String msg) {
7894        Slog.println(priority, TAG, msg);
7895        EventLogTags.writePmCriticalInfo(msg);
7896        try {
7897            File fname = getSettingsProblemFile();
7898            FileOutputStream out = new FileOutputStream(fname, true);
7899            PrintWriter pw = new FastPrintWriter(out);
7900            SimpleDateFormat formatter = new SimpleDateFormat();
7901            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7902            pw.println(dateString + ": " + msg);
7903            pw.close();
7904            FileUtils.setPermissions(
7905                    fname.toString(),
7906                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7907                    -1, -1);
7908        } catch (java.io.IOException e) {
7909        }
7910    }
7911
7912    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7913        if (srcFile.isDirectory()) {
7914            final File baseFile = new File(pkg.baseCodePath);
7915            long maxModifiedTime = baseFile.lastModified();
7916            if (pkg.splitCodePaths != null) {
7917                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7918                    final File splitFile = new File(pkg.splitCodePaths[i]);
7919                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7920                }
7921            }
7922            return maxModifiedTime;
7923        }
7924        return srcFile.lastModified();
7925    }
7926
7927    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7928            final int policyFlags) throws PackageManagerException {
7929        // When upgrading from pre-N MR1, verify the package time stamp using the package
7930        // directory and not the APK file.
7931        final long lastModifiedTime = mIsPreNMR1Upgrade
7932                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7933        if (ps != null
7934                && ps.codePath.equals(srcFile)
7935                && ps.timeStamp == lastModifiedTime
7936                && !isCompatSignatureUpdateNeeded(pkg)
7937                && !isRecoverSignatureUpdateNeeded(pkg)) {
7938            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7939            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7940            ArraySet<PublicKey> signingKs;
7941            synchronized (mPackages) {
7942                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7943            }
7944            if (ps.signatures.mSignatures != null
7945                    && ps.signatures.mSignatures.length != 0
7946                    && signingKs != null) {
7947                // Optimization: reuse the existing cached certificates
7948                // if the package appears to be unchanged.
7949                pkg.mSignatures = ps.signatures.mSignatures;
7950                pkg.mSigningKeys = signingKs;
7951                return;
7952            }
7953
7954            Slog.w(TAG, "PackageSetting for " + ps.name
7955                    + " is missing signatures.  Collecting certs again to recover them.");
7956        } else {
7957            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7958        }
7959
7960        try {
7961            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7962            PackageParser.collectCertificates(pkg, policyFlags);
7963        } catch (PackageParserException e) {
7964            throw PackageManagerException.from(e);
7965        } finally {
7966            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7967        }
7968    }
7969
7970    /**
7971     *  Traces a package scan.
7972     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7973     */
7974    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7975            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7976        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7977        try {
7978            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7979        } finally {
7980            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7981        }
7982    }
7983
7984    /**
7985     *  Scans a package and returns the newly parsed package.
7986     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7987     */
7988    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7989            long currentTime, UserHandle user) throws PackageManagerException {
7990        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7991        PackageParser pp = new PackageParser();
7992        pp.setSeparateProcesses(mSeparateProcesses);
7993        pp.setOnlyCoreApps(mOnlyCore);
7994        pp.setDisplayMetrics(mMetrics);
7995        pp.setCallback(mPackageParserCallback);
7996
7997        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7998            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7999        }
8000
8001        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8002        final PackageParser.Package pkg;
8003        try {
8004            pkg = pp.parsePackage(scanFile, parseFlags);
8005        } catch (PackageParserException e) {
8006            throw PackageManagerException.from(e);
8007        } finally {
8008            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8009        }
8010
8011        // Static shared libraries have synthetic package names
8012        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8013            renameStaticSharedLibraryPackage(pkg);
8014        }
8015
8016        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8017    }
8018
8019    /**
8020     *  Scans a package and returns the newly parsed package.
8021     *  @throws PackageManagerException on a parse error.
8022     */
8023    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8024            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8025            throws PackageManagerException {
8026        // If the package has children and this is the first dive in the function
8027        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8028        // packages (parent and children) would be successfully scanned before the
8029        // actual scan since scanning mutates internal state and we want to atomically
8030        // install the package and its children.
8031        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8032            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8033                scanFlags |= SCAN_CHECK_ONLY;
8034            }
8035        } else {
8036            scanFlags &= ~SCAN_CHECK_ONLY;
8037        }
8038
8039        // Scan the parent
8040        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8041                scanFlags, currentTime, user);
8042
8043        // Scan the children
8044        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8045        for (int i = 0; i < childCount; i++) {
8046            PackageParser.Package childPackage = pkg.childPackages.get(i);
8047            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8048                    currentTime, user);
8049        }
8050
8051
8052        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8053            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8054        }
8055
8056        return scannedPkg;
8057    }
8058
8059    /**
8060     *  Scans a package and returns the newly parsed package.
8061     *  @throws PackageManagerException on a parse error.
8062     */
8063    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8064            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8065            throws PackageManagerException {
8066        PackageSetting ps = null;
8067        PackageSetting updatedPkg;
8068        // reader
8069        synchronized (mPackages) {
8070            // Look to see if we already know about this package.
8071            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8072            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8073                // This package has been renamed to its original name.  Let's
8074                // use that.
8075                ps = mSettings.getPackageLPr(oldName);
8076            }
8077            // If there was no original package, see one for the real package name.
8078            if (ps == null) {
8079                ps = mSettings.getPackageLPr(pkg.packageName);
8080            }
8081            // Check to see if this package could be hiding/updating a system
8082            // package.  Must look for it either under the original or real
8083            // package name depending on our state.
8084            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8085            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8086
8087            // If this is a package we don't know about on the system partition, we
8088            // may need to remove disabled child packages on the system partition
8089            // or may need to not add child packages if the parent apk is updated
8090            // on the data partition and no longer defines this child package.
8091            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8092                // If this is a parent package for an updated system app and this system
8093                // app got an OTA update which no longer defines some of the child packages
8094                // we have to prune them from the disabled system packages.
8095                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8096                if (disabledPs != null) {
8097                    final int scannedChildCount = (pkg.childPackages != null)
8098                            ? pkg.childPackages.size() : 0;
8099                    final int disabledChildCount = disabledPs.childPackageNames != null
8100                            ? disabledPs.childPackageNames.size() : 0;
8101                    for (int i = 0; i < disabledChildCount; i++) {
8102                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8103                        boolean disabledPackageAvailable = false;
8104                        for (int j = 0; j < scannedChildCount; j++) {
8105                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8106                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8107                                disabledPackageAvailable = true;
8108                                break;
8109                            }
8110                         }
8111                         if (!disabledPackageAvailable) {
8112                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8113                         }
8114                    }
8115                }
8116            }
8117        }
8118
8119        boolean updatedPkgBetter = false;
8120        // First check if this is a system package that may involve an update
8121        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8122            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8123            // it needs to drop FLAG_PRIVILEGED.
8124            if (locationIsPrivileged(scanFile)) {
8125                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8126            } else {
8127                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8128            }
8129
8130            if (ps != null && !ps.codePath.equals(scanFile)) {
8131                // The path has changed from what was last scanned...  check the
8132                // version of the new path against what we have stored to determine
8133                // what to do.
8134                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8135                if (pkg.mVersionCode <= ps.versionCode) {
8136                    // The system package has been updated and the code path does not match
8137                    // Ignore entry. Skip it.
8138                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8139                            + " ignored: updated version " + ps.versionCode
8140                            + " better than this " + pkg.mVersionCode);
8141                    if (!updatedPkg.codePath.equals(scanFile)) {
8142                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8143                                + ps.name + " changing from " + updatedPkg.codePathString
8144                                + " to " + scanFile);
8145                        updatedPkg.codePath = scanFile;
8146                        updatedPkg.codePathString = scanFile.toString();
8147                        updatedPkg.resourcePath = scanFile;
8148                        updatedPkg.resourcePathString = scanFile.toString();
8149                    }
8150                    updatedPkg.pkg = pkg;
8151                    updatedPkg.versionCode = pkg.mVersionCode;
8152
8153                    // Update the disabled system child packages to point to the package too.
8154                    final int childCount = updatedPkg.childPackageNames != null
8155                            ? updatedPkg.childPackageNames.size() : 0;
8156                    for (int i = 0; i < childCount; i++) {
8157                        String childPackageName = updatedPkg.childPackageNames.get(i);
8158                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8159                                childPackageName);
8160                        if (updatedChildPkg != null) {
8161                            updatedChildPkg.pkg = pkg;
8162                            updatedChildPkg.versionCode = pkg.mVersionCode;
8163                        }
8164                    }
8165
8166                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8167                            + scanFile + " ignored: updated version " + ps.versionCode
8168                            + " better than this " + pkg.mVersionCode);
8169                } else {
8170                    // The current app on the system partition is better than
8171                    // what we have updated to on the data partition; switch
8172                    // back to the system partition version.
8173                    // At this point, its safely assumed that package installation for
8174                    // apps in system partition will go through. If not there won't be a working
8175                    // version of the app
8176                    // writer
8177                    synchronized (mPackages) {
8178                        // Just remove the loaded entries from package lists.
8179                        mPackages.remove(ps.name);
8180                    }
8181
8182                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8183                            + " reverting from " + ps.codePathString
8184                            + ": new version " + pkg.mVersionCode
8185                            + " better than installed " + ps.versionCode);
8186
8187                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8188                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8189                    synchronized (mInstallLock) {
8190                        args.cleanUpResourcesLI();
8191                    }
8192                    synchronized (mPackages) {
8193                        mSettings.enableSystemPackageLPw(ps.name);
8194                    }
8195                    updatedPkgBetter = true;
8196                }
8197            }
8198        }
8199
8200        if (updatedPkg != null) {
8201            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8202            // initially
8203            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8204
8205            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8206            // flag set initially
8207            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8208                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8209            }
8210        }
8211
8212        // Verify certificates against what was last scanned
8213        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8214
8215        /*
8216         * A new system app appeared, but we already had a non-system one of the
8217         * same name installed earlier.
8218         */
8219        boolean shouldHideSystemApp = false;
8220        if (updatedPkg == null && ps != null
8221                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8222            /*
8223             * Check to make sure the signatures match first. If they don't,
8224             * wipe the installed application and its data.
8225             */
8226            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8227                    != PackageManager.SIGNATURE_MATCH) {
8228                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8229                        + " signatures don't match existing userdata copy; removing");
8230                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8231                        "scanPackageInternalLI")) {
8232                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8233                }
8234                ps = null;
8235            } else {
8236                /*
8237                 * If the newly-added system app is an older version than the
8238                 * already installed version, hide it. It will be scanned later
8239                 * and re-added like an update.
8240                 */
8241                if (pkg.mVersionCode <= ps.versionCode) {
8242                    shouldHideSystemApp = true;
8243                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8244                            + " but new version " + pkg.mVersionCode + " better than installed "
8245                            + ps.versionCode + "; hiding system");
8246                } else {
8247                    /*
8248                     * The newly found system app is a newer version that the
8249                     * one previously installed. Simply remove the
8250                     * already-installed application and replace it with our own
8251                     * while keeping the application data.
8252                     */
8253                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8254                            + " reverting from " + ps.codePathString + ": new version "
8255                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8256                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8257                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8258                    synchronized (mInstallLock) {
8259                        args.cleanUpResourcesLI();
8260                    }
8261                }
8262            }
8263        }
8264
8265        // The apk is forward locked (not public) if its code and resources
8266        // are kept in different files. (except for app in either system or
8267        // vendor path).
8268        // TODO grab this value from PackageSettings
8269        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8270            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8271                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8272            }
8273        }
8274
8275        // TODO: extend to support forward-locked splits
8276        String resourcePath = null;
8277        String baseResourcePath = null;
8278        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8279            if (ps != null && ps.resourcePathString != null) {
8280                resourcePath = ps.resourcePathString;
8281                baseResourcePath = ps.resourcePathString;
8282            } else {
8283                // Should not happen at all. Just log an error.
8284                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8285            }
8286        } else {
8287            resourcePath = pkg.codePath;
8288            baseResourcePath = pkg.baseCodePath;
8289        }
8290
8291        // Set application objects path explicitly.
8292        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8293        pkg.setApplicationInfoCodePath(pkg.codePath);
8294        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8295        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8296        pkg.setApplicationInfoResourcePath(resourcePath);
8297        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8298        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8299
8300        final int userId = ((user == null) ? 0 : user.getIdentifier());
8301        if (ps != null && ps.getInstantApp(userId)) {
8302            scanFlags |= SCAN_AS_INSTANT_APP;
8303        }
8304
8305        // Note that we invoke the following method only if we are about to unpack an application
8306        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8307                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8308
8309        /*
8310         * If the system app should be overridden by a previously installed
8311         * data, hide the system app now and let the /data/app scan pick it up
8312         * again.
8313         */
8314        if (shouldHideSystemApp) {
8315            synchronized (mPackages) {
8316                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8317            }
8318        }
8319
8320        return scannedPkg;
8321    }
8322
8323    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8324        // Derive the new package synthetic package name
8325        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8326                + pkg.staticSharedLibVersion);
8327    }
8328
8329    private static String fixProcessName(String defProcessName,
8330            String processName) {
8331        if (processName == null) {
8332            return defProcessName;
8333        }
8334        return processName;
8335    }
8336
8337    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8338            throws PackageManagerException {
8339        if (pkgSetting.signatures.mSignatures != null) {
8340            // Already existing package. Make sure signatures match
8341            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8342                    == PackageManager.SIGNATURE_MATCH;
8343            if (!match) {
8344                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8345                        == PackageManager.SIGNATURE_MATCH;
8346            }
8347            if (!match) {
8348                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8349                        == PackageManager.SIGNATURE_MATCH;
8350            }
8351            if (!match) {
8352                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8353                        + pkg.packageName + " signatures do not match the "
8354                        + "previously installed version; ignoring!");
8355            }
8356        }
8357
8358        // Check for shared user signatures
8359        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8360            // Already existing package. Make sure signatures match
8361            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8362                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8363            if (!match) {
8364                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8365                        == PackageManager.SIGNATURE_MATCH;
8366            }
8367            if (!match) {
8368                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8369                        == PackageManager.SIGNATURE_MATCH;
8370            }
8371            if (!match) {
8372                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8373                        "Package " + pkg.packageName
8374                        + " has no signatures that match those in shared user "
8375                        + pkgSetting.sharedUser.name + "; ignoring!");
8376            }
8377        }
8378    }
8379
8380    /**
8381     * Enforces that only the system UID or root's UID can call a method exposed
8382     * via Binder.
8383     *
8384     * @param message used as message if SecurityException is thrown
8385     * @throws SecurityException if the caller is not system or root
8386     */
8387    private static final void enforceSystemOrRoot(String message) {
8388        final int uid = Binder.getCallingUid();
8389        if (uid != Process.SYSTEM_UID && uid != 0) {
8390            throw new SecurityException(message);
8391        }
8392    }
8393
8394    @Override
8395    public void performFstrimIfNeeded() {
8396        enforceSystemOrRoot("Only the system can request fstrim");
8397
8398        // Before everything else, see whether we need to fstrim.
8399        try {
8400            IStorageManager sm = PackageHelper.getStorageManager();
8401            if (sm != null) {
8402                boolean doTrim = false;
8403                final long interval = android.provider.Settings.Global.getLong(
8404                        mContext.getContentResolver(),
8405                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8406                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8407                if (interval > 0) {
8408                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8409                    if (timeSinceLast > interval) {
8410                        doTrim = true;
8411                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8412                                + "; running immediately");
8413                    }
8414                }
8415                if (doTrim) {
8416                    final boolean dexOptDialogShown;
8417                    synchronized (mPackages) {
8418                        dexOptDialogShown = mDexOptDialogShown;
8419                    }
8420                    if (!isFirstBoot() && dexOptDialogShown) {
8421                        try {
8422                            ActivityManager.getService().showBootMessage(
8423                                    mContext.getResources().getString(
8424                                            R.string.android_upgrading_fstrim), true);
8425                        } catch (RemoteException e) {
8426                        }
8427                    }
8428                    sm.runMaintenance();
8429                }
8430            } else {
8431                Slog.e(TAG, "storageManager service unavailable!");
8432            }
8433        } catch (RemoteException e) {
8434            // Can't happen; StorageManagerService is local
8435        }
8436    }
8437
8438    @Override
8439    public void updatePackagesIfNeeded() {
8440        enforceSystemOrRoot("Only the system can request package update");
8441
8442        // We need to re-extract after an OTA.
8443        boolean causeUpgrade = isUpgrade();
8444
8445        // First boot or factory reset.
8446        // Note: we also handle devices that are upgrading to N right now as if it is their
8447        //       first boot, as they do not have profile data.
8448        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8449
8450        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8451        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8452
8453        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8454            return;
8455        }
8456
8457        List<PackageParser.Package> pkgs;
8458        synchronized (mPackages) {
8459            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8460        }
8461
8462        final long startTime = System.nanoTime();
8463        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8464                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8465
8466        final int elapsedTimeSeconds =
8467                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8468
8469        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8470        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8471        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8472        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8473        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8474    }
8475
8476    /**
8477     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8478     * containing statistics about the invocation. The array consists of three elements,
8479     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8480     * and {@code numberOfPackagesFailed}.
8481     */
8482    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8483            String compilerFilter) {
8484
8485        int numberOfPackagesVisited = 0;
8486        int numberOfPackagesOptimized = 0;
8487        int numberOfPackagesSkipped = 0;
8488        int numberOfPackagesFailed = 0;
8489        final int numberOfPackagesToDexopt = pkgs.size();
8490
8491        for (PackageParser.Package pkg : pkgs) {
8492            numberOfPackagesVisited++;
8493
8494            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8495                if (DEBUG_DEXOPT) {
8496                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8497                }
8498                numberOfPackagesSkipped++;
8499                continue;
8500            }
8501
8502            if (DEBUG_DEXOPT) {
8503                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8504                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8505            }
8506
8507            if (showDialog) {
8508                try {
8509                    ActivityManager.getService().showBootMessage(
8510                            mContext.getResources().getString(R.string.android_upgrading_apk,
8511                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8512                } catch (RemoteException e) {
8513                }
8514                synchronized (mPackages) {
8515                    mDexOptDialogShown = true;
8516                }
8517            }
8518
8519            // If the OTA updates a system app which was previously preopted to a non-preopted state
8520            // the app might end up being verified at runtime. That's because by default the apps
8521            // are verify-profile but for preopted apps there's no profile.
8522            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8523            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8524            // filter (by default interpret-only).
8525            // Note that at this stage unused apps are already filtered.
8526            if (isSystemApp(pkg) &&
8527                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8528                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8529                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8530            }
8531
8532            // checkProfiles is false to avoid merging profiles during boot which
8533            // might interfere with background compilation (b/28612421).
8534            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8535            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8536            // trade-off worth doing to save boot time work.
8537            int dexOptStatus = performDexOptTraced(pkg.packageName,
8538                    false /* checkProfiles */,
8539                    compilerFilter,
8540                    false /* force */);
8541            switch (dexOptStatus) {
8542                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8543                    numberOfPackagesOptimized++;
8544                    break;
8545                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8546                    numberOfPackagesSkipped++;
8547                    break;
8548                case PackageDexOptimizer.DEX_OPT_FAILED:
8549                    numberOfPackagesFailed++;
8550                    break;
8551                default:
8552                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8553                    break;
8554            }
8555        }
8556
8557        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8558                numberOfPackagesFailed };
8559    }
8560
8561    @Override
8562    public void notifyPackageUse(String packageName, int reason) {
8563        synchronized (mPackages) {
8564            PackageParser.Package p = mPackages.get(packageName);
8565            if (p == null) {
8566                return;
8567            }
8568            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8569        }
8570    }
8571
8572    @Override
8573    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8574        int userId = UserHandle.getCallingUserId();
8575        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8576        if (ai == null) {
8577            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8578                + loadingPackageName + ", user=" + userId);
8579            return;
8580        }
8581        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8582    }
8583
8584    // TODO: this is not used nor needed. Delete it.
8585    @Override
8586    public boolean performDexOptIfNeeded(String packageName) {
8587        int dexOptStatus = performDexOptTraced(packageName,
8588                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8589        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8590    }
8591
8592    @Override
8593    public boolean performDexOpt(String packageName,
8594            boolean checkProfiles, int compileReason, boolean force) {
8595        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8596                getCompilerFilterForReason(compileReason), force);
8597        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8598    }
8599
8600    @Override
8601    public boolean performDexOptMode(String packageName,
8602            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8603        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8604                targetCompilerFilter, force);
8605        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8606    }
8607
8608    private int performDexOptTraced(String packageName,
8609                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8610        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8611        try {
8612            return performDexOptInternal(packageName, checkProfiles,
8613                    targetCompilerFilter, force);
8614        } finally {
8615            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8616        }
8617    }
8618
8619    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8620    // if the package can now be considered up to date for the given filter.
8621    private int performDexOptInternal(String packageName,
8622                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8623        PackageParser.Package p;
8624        synchronized (mPackages) {
8625            p = mPackages.get(packageName);
8626            if (p == null) {
8627                // Package could not be found. Report failure.
8628                return PackageDexOptimizer.DEX_OPT_FAILED;
8629            }
8630            mPackageUsage.maybeWriteAsync(mPackages);
8631            mCompilerStats.maybeWriteAsync();
8632        }
8633        long callingId = Binder.clearCallingIdentity();
8634        try {
8635            synchronized (mInstallLock) {
8636                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8637                        targetCompilerFilter, force);
8638            }
8639        } finally {
8640            Binder.restoreCallingIdentity(callingId);
8641        }
8642    }
8643
8644    public ArraySet<String> getOptimizablePackages() {
8645        ArraySet<String> pkgs = new ArraySet<String>();
8646        synchronized (mPackages) {
8647            for (PackageParser.Package p : mPackages.values()) {
8648                if (PackageDexOptimizer.canOptimizePackage(p)) {
8649                    pkgs.add(p.packageName);
8650                }
8651            }
8652        }
8653        return pkgs;
8654    }
8655
8656    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8657            boolean checkProfiles, String targetCompilerFilter,
8658            boolean force) {
8659        // Select the dex optimizer based on the force parameter.
8660        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8661        //       allocate an object here.
8662        PackageDexOptimizer pdo = force
8663                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8664                : mPackageDexOptimizer;
8665
8666        // Dexopt all dependencies first. Note: we ignore the return value and march on
8667        // on errors.
8668        // Note that we are going to call performDexOpt on those libraries as many times as
8669        // they are referenced in packages. When we do a batch of performDexOpt (for example
8670        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8671        // and the first package that uses the library will dexopt it. The
8672        // others will see that the compiled code for the library is up to date.
8673        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8674        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8675        if (!deps.isEmpty()) {
8676            for (PackageParser.Package depPackage : deps) {
8677                // TODO: Analyze and investigate if we (should) profile libraries.
8678                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8679                        false /* checkProfiles */,
8680                        targetCompilerFilter,
8681                        getOrCreateCompilerPackageStats(depPackage),
8682                        true /* isUsedByOtherApps */);
8683            }
8684        }
8685        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8686                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8687                mDexManager.isUsedByOtherApps(p.packageName));
8688    }
8689
8690    // Performs dexopt on the used secondary dex files belonging to the given package.
8691    // Returns true if all dex files were process successfully (which could mean either dexopt or
8692    // skip). Returns false if any of the files caused errors.
8693    @Override
8694    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8695            boolean force) {
8696        mDexManager.reconcileSecondaryDexFiles(packageName);
8697        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8698    }
8699
8700    public boolean performDexOptSecondary(String packageName, int compileReason,
8701            boolean force) {
8702        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8703    }
8704
8705    /**
8706     * Reconcile the information we have about the secondary dex files belonging to
8707     * {@code packagName} and the actual dex files. For all dex files that were
8708     * deleted, update the internal records and delete the generated oat files.
8709     */
8710    @Override
8711    public void reconcileSecondaryDexFiles(String packageName) {
8712        mDexManager.reconcileSecondaryDexFiles(packageName);
8713    }
8714
8715    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8716    // a reference there.
8717    /*package*/ DexManager getDexManager() {
8718        return mDexManager;
8719    }
8720
8721    /**
8722     * Execute the background dexopt job immediately.
8723     */
8724    @Override
8725    public boolean runBackgroundDexoptJob() {
8726        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8727    }
8728
8729    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8730        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8731                || p.usesStaticLibraries != null) {
8732            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8733            Set<String> collectedNames = new HashSet<>();
8734            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8735
8736            retValue.remove(p);
8737
8738            return retValue;
8739        } else {
8740            return Collections.emptyList();
8741        }
8742    }
8743
8744    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8745            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8746        if (!collectedNames.contains(p.packageName)) {
8747            collectedNames.add(p.packageName);
8748            collected.add(p);
8749
8750            if (p.usesLibraries != null) {
8751                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8752                        null, collected, collectedNames);
8753            }
8754            if (p.usesOptionalLibraries != null) {
8755                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8756                        null, collected, collectedNames);
8757            }
8758            if (p.usesStaticLibraries != null) {
8759                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8760                        p.usesStaticLibrariesVersions, collected, collectedNames);
8761            }
8762        }
8763    }
8764
8765    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8766            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8767        final int libNameCount = libs.size();
8768        for (int i = 0; i < libNameCount; i++) {
8769            String libName = libs.get(i);
8770            int version = (versions != null && versions.length == libNameCount)
8771                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8772            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8773            if (libPkg != null) {
8774                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8775            }
8776        }
8777    }
8778
8779    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8780        synchronized (mPackages) {
8781            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8782            if (libEntry != null) {
8783                return mPackages.get(libEntry.apk);
8784            }
8785            return null;
8786        }
8787    }
8788
8789    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8790        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8791        if (versionedLib == null) {
8792            return null;
8793        }
8794        return versionedLib.get(version);
8795    }
8796
8797    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8798        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8799                pkg.staticSharedLibName);
8800        if (versionedLib == null) {
8801            return null;
8802        }
8803        int previousLibVersion = -1;
8804        final int versionCount = versionedLib.size();
8805        for (int i = 0; i < versionCount; i++) {
8806            final int libVersion = versionedLib.keyAt(i);
8807            if (libVersion < pkg.staticSharedLibVersion) {
8808                previousLibVersion = Math.max(previousLibVersion, libVersion);
8809            }
8810        }
8811        if (previousLibVersion >= 0) {
8812            return versionedLib.get(previousLibVersion);
8813        }
8814        return null;
8815    }
8816
8817    public void shutdown() {
8818        mPackageUsage.writeNow(mPackages);
8819        mCompilerStats.writeNow();
8820    }
8821
8822    @Override
8823    public void dumpProfiles(String packageName) {
8824        PackageParser.Package pkg;
8825        synchronized (mPackages) {
8826            pkg = mPackages.get(packageName);
8827            if (pkg == null) {
8828                throw new IllegalArgumentException("Unknown package: " + packageName);
8829            }
8830        }
8831        /* Only the shell, root, or the app user should be able to dump profiles. */
8832        int callingUid = Binder.getCallingUid();
8833        if (callingUid != Process.SHELL_UID &&
8834            callingUid != Process.ROOT_UID &&
8835            callingUid != pkg.applicationInfo.uid) {
8836            throw new SecurityException("dumpProfiles");
8837        }
8838
8839        synchronized (mInstallLock) {
8840            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8841            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8842            try {
8843                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8844                String codePaths = TextUtils.join(";", allCodePaths);
8845                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8846            } catch (InstallerException e) {
8847                Slog.w(TAG, "Failed to dump profiles", e);
8848            }
8849            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8850        }
8851    }
8852
8853    @Override
8854    public void forceDexOpt(String packageName) {
8855        enforceSystemOrRoot("forceDexOpt");
8856
8857        PackageParser.Package pkg;
8858        synchronized (mPackages) {
8859            pkg = mPackages.get(packageName);
8860            if (pkg == null) {
8861                throw new IllegalArgumentException("Unknown package: " + packageName);
8862            }
8863        }
8864
8865        synchronized (mInstallLock) {
8866            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8867
8868            // Whoever is calling forceDexOpt wants a fully compiled package.
8869            // Don't use profiles since that may cause compilation to be skipped.
8870            final int res = performDexOptInternalWithDependenciesLI(pkg,
8871                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8872                    true /* force */);
8873
8874            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8875            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8876                throw new IllegalStateException("Failed to dexopt: " + res);
8877            }
8878        }
8879    }
8880
8881    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8882        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8883            Slog.w(TAG, "Unable to update from " + oldPkg.name
8884                    + " to " + newPkg.packageName
8885                    + ": old package not in system partition");
8886            return false;
8887        } else if (mPackages.get(oldPkg.name) != null) {
8888            Slog.w(TAG, "Unable to update from " + oldPkg.name
8889                    + " to " + newPkg.packageName
8890                    + ": old package still exists");
8891            return false;
8892        }
8893        return true;
8894    }
8895
8896    void removeCodePathLI(File codePath) {
8897        if (codePath.isDirectory()) {
8898            try {
8899                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8900            } catch (InstallerException e) {
8901                Slog.w(TAG, "Failed to remove code path", e);
8902            }
8903        } else {
8904            codePath.delete();
8905        }
8906    }
8907
8908    private int[] resolveUserIds(int userId) {
8909        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8910    }
8911
8912    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8913        if (pkg == null) {
8914            Slog.wtf(TAG, "Package was null!", new Throwable());
8915            return;
8916        }
8917        clearAppDataLeafLIF(pkg, userId, flags);
8918        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8919        for (int i = 0; i < childCount; i++) {
8920            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8921        }
8922    }
8923
8924    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8925        final PackageSetting ps;
8926        synchronized (mPackages) {
8927            ps = mSettings.mPackages.get(pkg.packageName);
8928        }
8929        for (int realUserId : resolveUserIds(userId)) {
8930            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8931            try {
8932                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8933                        ceDataInode);
8934            } catch (InstallerException e) {
8935                Slog.w(TAG, String.valueOf(e));
8936            }
8937        }
8938    }
8939
8940    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8941        if (pkg == null) {
8942            Slog.wtf(TAG, "Package was null!", new Throwable());
8943            return;
8944        }
8945        destroyAppDataLeafLIF(pkg, userId, flags);
8946        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8947        for (int i = 0; i < childCount; i++) {
8948            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8949        }
8950    }
8951
8952    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8953        final PackageSetting ps;
8954        synchronized (mPackages) {
8955            ps = mSettings.mPackages.get(pkg.packageName);
8956        }
8957        for (int realUserId : resolveUserIds(userId)) {
8958            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8959            try {
8960                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8961                        ceDataInode);
8962            } catch (InstallerException e) {
8963                Slog.w(TAG, String.valueOf(e));
8964            }
8965            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8966        }
8967    }
8968
8969    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8970        if (pkg == null) {
8971            Slog.wtf(TAG, "Package was null!", new Throwable());
8972            return;
8973        }
8974        destroyAppProfilesLeafLIF(pkg);
8975        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8976        for (int i = 0; i < childCount; i++) {
8977            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8978        }
8979    }
8980
8981    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8982        try {
8983            mInstaller.destroyAppProfiles(pkg.packageName);
8984        } catch (InstallerException e) {
8985            Slog.w(TAG, String.valueOf(e));
8986        }
8987    }
8988
8989    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8990        if (pkg == null) {
8991            Slog.wtf(TAG, "Package was null!", new Throwable());
8992            return;
8993        }
8994        clearAppProfilesLeafLIF(pkg);
8995        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8996        for (int i = 0; i < childCount; i++) {
8997            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8998        }
8999    }
9000
9001    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9002        try {
9003            mInstaller.clearAppProfiles(pkg.packageName);
9004        } catch (InstallerException e) {
9005            Slog.w(TAG, String.valueOf(e));
9006        }
9007    }
9008
9009    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9010            long lastUpdateTime) {
9011        // Set parent install/update time
9012        PackageSetting ps = (PackageSetting) pkg.mExtras;
9013        if (ps != null) {
9014            ps.firstInstallTime = firstInstallTime;
9015            ps.lastUpdateTime = lastUpdateTime;
9016        }
9017        // Set children install/update time
9018        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9019        for (int i = 0; i < childCount; i++) {
9020            PackageParser.Package childPkg = pkg.childPackages.get(i);
9021            ps = (PackageSetting) childPkg.mExtras;
9022            if (ps != null) {
9023                ps.firstInstallTime = firstInstallTime;
9024                ps.lastUpdateTime = lastUpdateTime;
9025            }
9026        }
9027    }
9028
9029    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9030            PackageParser.Package changingLib) {
9031        if (file.path != null) {
9032            usesLibraryFiles.add(file.path);
9033            return;
9034        }
9035        PackageParser.Package p = mPackages.get(file.apk);
9036        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9037            // If we are doing this while in the middle of updating a library apk,
9038            // then we need to make sure to use that new apk for determining the
9039            // dependencies here.  (We haven't yet finished committing the new apk
9040            // to the package manager state.)
9041            if (p == null || p.packageName.equals(changingLib.packageName)) {
9042                p = changingLib;
9043            }
9044        }
9045        if (p != null) {
9046            usesLibraryFiles.addAll(p.getAllCodePaths());
9047        }
9048    }
9049
9050    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9051            PackageParser.Package changingLib) throws PackageManagerException {
9052        if (pkg == null) {
9053            return;
9054        }
9055        ArraySet<String> usesLibraryFiles = null;
9056        if (pkg.usesLibraries != null) {
9057            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9058                    null, null, pkg.packageName, changingLib, true, null);
9059        }
9060        if (pkg.usesStaticLibraries != null) {
9061            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9062                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9063                    pkg.packageName, changingLib, true, usesLibraryFiles);
9064        }
9065        if (pkg.usesOptionalLibraries != null) {
9066            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9067                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9068        }
9069        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9070            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9071        } else {
9072            pkg.usesLibraryFiles = null;
9073        }
9074    }
9075
9076    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9077            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9078            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9079            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9080            throws PackageManagerException {
9081        final int libCount = requestedLibraries.size();
9082        for (int i = 0; i < libCount; i++) {
9083            final String libName = requestedLibraries.get(i);
9084            final int libVersion = requiredVersions != null ? requiredVersions[i]
9085                    : SharedLibraryInfo.VERSION_UNDEFINED;
9086            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9087            if (libEntry == null) {
9088                if (required) {
9089                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9090                            "Package " + packageName + " requires unavailable shared library "
9091                                    + libName + "; failing!");
9092                } else {
9093                    Slog.w(TAG, "Package " + packageName
9094                            + " desires unavailable shared library "
9095                            + libName + "; ignoring!");
9096                }
9097            } else {
9098                if (requiredVersions != null && requiredCertDigests != null) {
9099                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9100                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9101                            "Package " + packageName + " requires unavailable static shared"
9102                                    + " library " + libName + " version "
9103                                    + libEntry.info.getVersion() + "; failing!");
9104                    }
9105
9106                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9107                    if (libPkg == null) {
9108                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9109                                "Package " + packageName + " requires unavailable static shared"
9110                                        + " library; failing!");
9111                    }
9112
9113                    String expectedCertDigest = requiredCertDigests[i];
9114                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9115                                libPkg.mSignatures[0]);
9116                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9117                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9118                                "Package " + packageName + " requires differently signed" +
9119                                        " static shared library; failing!");
9120                    }
9121                }
9122
9123                if (outUsedLibraries == null) {
9124                    outUsedLibraries = new ArraySet<>();
9125                }
9126                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9127            }
9128        }
9129        return outUsedLibraries;
9130    }
9131
9132    private static boolean hasString(List<String> list, List<String> which) {
9133        if (list == null) {
9134            return false;
9135        }
9136        for (int i=list.size()-1; i>=0; i--) {
9137            for (int j=which.size()-1; j>=0; j--) {
9138                if (which.get(j).equals(list.get(i))) {
9139                    return true;
9140                }
9141            }
9142        }
9143        return false;
9144    }
9145
9146    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9147            PackageParser.Package changingPkg) {
9148        ArrayList<PackageParser.Package> res = null;
9149        for (PackageParser.Package pkg : mPackages.values()) {
9150            if (changingPkg != null
9151                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9152                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9153                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9154                            changingPkg.staticSharedLibName)) {
9155                return null;
9156            }
9157            if (res == null) {
9158                res = new ArrayList<>();
9159            }
9160            res.add(pkg);
9161            try {
9162                updateSharedLibrariesLPr(pkg, changingPkg);
9163            } catch (PackageManagerException e) {
9164                // If a system app update or an app and a required lib missing we
9165                // delete the package and for updated system apps keep the data as
9166                // it is better for the user to reinstall than to be in an limbo
9167                // state. Also libs disappearing under an app should never happen
9168                // - just in case.
9169                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9170                    final int flags = pkg.isUpdatedSystemApp()
9171                            ? PackageManager.DELETE_KEEP_DATA : 0;
9172                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9173                            flags , null, true, null);
9174                }
9175                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9176            }
9177        }
9178        return res;
9179    }
9180
9181    /**
9182     * Derive the value of the {@code cpuAbiOverride} based on the provided
9183     * value and an optional stored value from the package settings.
9184     */
9185    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9186        String cpuAbiOverride = null;
9187
9188        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9189            cpuAbiOverride = null;
9190        } else if (abiOverride != null) {
9191            cpuAbiOverride = abiOverride;
9192        } else if (settings != null) {
9193            cpuAbiOverride = settings.cpuAbiOverrideString;
9194        }
9195
9196        return cpuAbiOverride;
9197    }
9198
9199    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9200            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9201                    throws PackageManagerException {
9202        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9203        // If the package has children and this is the first dive in the function
9204        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9205        // whether all packages (parent and children) would be successfully scanned
9206        // before the actual scan since scanning mutates internal state and we want
9207        // to atomically install the package and its children.
9208        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9209            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9210                scanFlags |= SCAN_CHECK_ONLY;
9211            }
9212        } else {
9213            scanFlags &= ~SCAN_CHECK_ONLY;
9214        }
9215
9216        final PackageParser.Package scannedPkg;
9217        try {
9218            // Scan the parent
9219            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9220            // Scan the children
9221            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9222            for (int i = 0; i < childCount; i++) {
9223                PackageParser.Package childPkg = pkg.childPackages.get(i);
9224                scanPackageLI(childPkg, policyFlags,
9225                        scanFlags, currentTime, user);
9226            }
9227        } finally {
9228            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9229        }
9230
9231        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9232            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9233        }
9234
9235        return scannedPkg;
9236    }
9237
9238    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9239            int scanFlags, long currentTime, @Nullable UserHandle user)
9240                    throws PackageManagerException {
9241        boolean success = false;
9242        try {
9243            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9244                    currentTime, user);
9245            success = true;
9246            return res;
9247        } finally {
9248            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9249                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9250                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9251                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9252                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9253            }
9254        }
9255    }
9256
9257    /**
9258     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9259     */
9260    private static boolean apkHasCode(String fileName) {
9261        StrictJarFile jarFile = null;
9262        try {
9263            jarFile = new StrictJarFile(fileName,
9264                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9265            return jarFile.findEntry("classes.dex") != null;
9266        } catch (IOException ignore) {
9267        } finally {
9268            try {
9269                if (jarFile != null) {
9270                    jarFile.close();
9271                }
9272            } catch (IOException ignore) {}
9273        }
9274        return false;
9275    }
9276
9277    /**
9278     * Enforces code policy for the package. This ensures that if an APK has
9279     * declared hasCode="true" in its manifest that the APK actually contains
9280     * code.
9281     *
9282     * @throws PackageManagerException If bytecode could not be found when it should exist
9283     */
9284    private static void assertCodePolicy(PackageParser.Package pkg)
9285            throws PackageManagerException {
9286        final boolean shouldHaveCode =
9287                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9288        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9289            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9290                    "Package " + pkg.baseCodePath + " code is missing");
9291        }
9292
9293        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9294            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9295                final boolean splitShouldHaveCode =
9296                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9297                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9298                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9299                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9300                }
9301            }
9302        }
9303    }
9304
9305    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9306            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9307                    throws PackageManagerException {
9308        if (DEBUG_PACKAGE_SCANNING) {
9309            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9310                Log.d(TAG, "Scanning package " + pkg.packageName);
9311        }
9312
9313        applyPolicy(pkg, policyFlags);
9314
9315        assertPackageIsValid(pkg, policyFlags, scanFlags);
9316
9317        // Initialize package source and resource directories
9318        final File scanFile = new File(pkg.codePath);
9319        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9320        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9321
9322        SharedUserSetting suid = null;
9323        PackageSetting pkgSetting = null;
9324
9325        // Getting the package setting may have a side-effect, so if we
9326        // are only checking if scan would succeed, stash a copy of the
9327        // old setting to restore at the end.
9328        PackageSetting nonMutatedPs = null;
9329
9330        // We keep references to the derived CPU Abis from settings in oder to reuse
9331        // them in the case where we're not upgrading or booting for the first time.
9332        String primaryCpuAbiFromSettings = null;
9333        String secondaryCpuAbiFromSettings = null;
9334
9335        // writer
9336        synchronized (mPackages) {
9337            if (pkg.mSharedUserId != null) {
9338                // SIDE EFFECTS; may potentially allocate a new shared user
9339                suid = mSettings.getSharedUserLPw(
9340                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9341                if (DEBUG_PACKAGE_SCANNING) {
9342                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9343                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9344                                + "): packages=" + suid.packages);
9345                }
9346            }
9347
9348            // Check if we are renaming from an original package name.
9349            PackageSetting origPackage = null;
9350            String realName = null;
9351            if (pkg.mOriginalPackages != null) {
9352                // This package may need to be renamed to a previously
9353                // installed name.  Let's check on that...
9354                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9355                if (pkg.mOriginalPackages.contains(renamed)) {
9356                    // This package had originally been installed as the
9357                    // original name, and we have already taken care of
9358                    // transitioning to the new one.  Just update the new
9359                    // one to continue using the old name.
9360                    realName = pkg.mRealPackage;
9361                    if (!pkg.packageName.equals(renamed)) {
9362                        // Callers into this function may have already taken
9363                        // care of renaming the package; only do it here if
9364                        // it is not already done.
9365                        pkg.setPackageName(renamed);
9366                    }
9367                } else {
9368                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9369                        if ((origPackage = mSettings.getPackageLPr(
9370                                pkg.mOriginalPackages.get(i))) != null) {
9371                            // We do have the package already installed under its
9372                            // original name...  should we use it?
9373                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9374                                // New package is not compatible with original.
9375                                origPackage = null;
9376                                continue;
9377                            } else if (origPackage.sharedUser != null) {
9378                                // Make sure uid is compatible between packages.
9379                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9380                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9381                                            + " to " + pkg.packageName + ": old uid "
9382                                            + origPackage.sharedUser.name
9383                                            + " differs from " + pkg.mSharedUserId);
9384                                    origPackage = null;
9385                                    continue;
9386                                }
9387                                // TODO: Add case when shared user id is added [b/28144775]
9388                            } else {
9389                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9390                                        + pkg.packageName + " to old name " + origPackage.name);
9391                            }
9392                            break;
9393                        }
9394                    }
9395                }
9396            }
9397
9398            if (mTransferedPackages.contains(pkg.packageName)) {
9399                Slog.w(TAG, "Package " + pkg.packageName
9400                        + " was transferred to another, but its .apk remains");
9401            }
9402
9403            // See comments in nonMutatedPs declaration
9404            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9405                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9406                if (foundPs != null) {
9407                    nonMutatedPs = new PackageSetting(foundPs);
9408                }
9409            }
9410
9411            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9412                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9413                if (foundPs != null) {
9414                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9415                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9416                }
9417            }
9418
9419            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9420            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9421                PackageManagerService.reportSettingsProblem(Log.WARN,
9422                        "Package " + pkg.packageName + " shared user changed from "
9423                                + (pkgSetting.sharedUser != null
9424                                        ? pkgSetting.sharedUser.name : "<nothing>")
9425                                + " to "
9426                                + (suid != null ? suid.name : "<nothing>")
9427                                + "; replacing with new");
9428                pkgSetting = null;
9429            }
9430            final PackageSetting oldPkgSetting =
9431                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9432            final PackageSetting disabledPkgSetting =
9433                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9434
9435            String[] usesStaticLibraries = null;
9436            if (pkg.usesStaticLibraries != null) {
9437                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9438                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9439            }
9440
9441            if (pkgSetting == null) {
9442                final String parentPackageName = (pkg.parentPackage != null)
9443                        ? pkg.parentPackage.packageName : null;
9444                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9445                // REMOVE SharedUserSetting from method; update in a separate call
9446                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9447                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9448                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9449                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9450                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9451                        true /*allowInstall*/, instantApp, parentPackageName,
9452                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9453                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9454                // SIDE EFFECTS; updates system state; move elsewhere
9455                if (origPackage != null) {
9456                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9457                }
9458                mSettings.addUserToSettingLPw(pkgSetting);
9459            } else {
9460                // REMOVE SharedUserSetting from method; update in a separate call.
9461                //
9462                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9463                // secondaryCpuAbi are not known at this point so we always update them
9464                // to null here, only to reset them at a later point.
9465                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9466                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9467                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9468                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9469                        UserManagerService.getInstance(), usesStaticLibraries,
9470                        pkg.usesStaticLibrariesVersions);
9471            }
9472            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9473            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9474
9475            // SIDE EFFECTS; modifies system state; move elsewhere
9476            if (pkgSetting.origPackage != null) {
9477                // If we are first transitioning from an original package,
9478                // fix up the new package's name now.  We need to do this after
9479                // looking up the package under its new name, so getPackageLP
9480                // can take care of fiddling things correctly.
9481                pkg.setPackageName(origPackage.name);
9482
9483                // File a report about this.
9484                String msg = "New package " + pkgSetting.realName
9485                        + " renamed to replace old package " + pkgSetting.name;
9486                reportSettingsProblem(Log.WARN, msg);
9487
9488                // Make a note of it.
9489                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9490                    mTransferedPackages.add(origPackage.name);
9491                }
9492
9493                // No longer need to retain this.
9494                pkgSetting.origPackage = null;
9495            }
9496
9497            // SIDE EFFECTS; modifies system state; move elsewhere
9498            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9499                // Make a note of it.
9500                mTransferedPackages.add(pkg.packageName);
9501            }
9502
9503            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9504                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9505            }
9506
9507            if ((scanFlags & SCAN_BOOTING) == 0
9508                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9509                // Check all shared libraries and map to their actual file path.
9510                // We only do this here for apps not on a system dir, because those
9511                // are the only ones that can fail an install due to this.  We
9512                // will take care of the system apps by updating all of their
9513                // library paths after the scan is done. Also during the initial
9514                // scan don't update any libs as we do this wholesale after all
9515                // apps are scanned to avoid dependency based scanning.
9516                updateSharedLibrariesLPr(pkg, null);
9517            }
9518
9519            if (mFoundPolicyFile) {
9520                SELinuxMMAC.assignSeInfoValue(pkg);
9521            }
9522            pkg.applicationInfo.uid = pkgSetting.appId;
9523            pkg.mExtras = pkgSetting;
9524
9525
9526            // Static shared libs have same package with different versions where
9527            // we internally use a synthetic package name to allow multiple versions
9528            // of the same package, therefore we need to compare signatures against
9529            // the package setting for the latest library version.
9530            PackageSetting signatureCheckPs = pkgSetting;
9531            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9532                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9533                if (libraryEntry != null) {
9534                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9535                }
9536            }
9537
9538            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9539                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9540                    // We just determined the app is signed correctly, so bring
9541                    // over the latest parsed certs.
9542                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9543                } else {
9544                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9545                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9546                                "Package " + pkg.packageName + " upgrade keys do not match the "
9547                                + "previously installed version");
9548                    } else {
9549                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9550                        String msg = "System package " + pkg.packageName
9551                                + " signature changed; retaining data.";
9552                        reportSettingsProblem(Log.WARN, msg);
9553                    }
9554                }
9555            } else {
9556                try {
9557                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9558                    verifySignaturesLP(signatureCheckPs, pkg);
9559                    // We just determined the app is signed correctly, so bring
9560                    // over the latest parsed certs.
9561                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9562                } catch (PackageManagerException e) {
9563                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9564                        throw e;
9565                    }
9566                    // The signature has changed, but this package is in the system
9567                    // image...  let's recover!
9568                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9569                    // However...  if this package is part of a shared user, but it
9570                    // doesn't match the signature of the shared user, let's fail.
9571                    // What this means is that you can't change the signatures
9572                    // associated with an overall shared user, which doesn't seem all
9573                    // that unreasonable.
9574                    if (signatureCheckPs.sharedUser != null) {
9575                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9576                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9577                            throw new PackageManagerException(
9578                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9579                                    "Signature mismatch for shared user: "
9580                                            + pkgSetting.sharedUser);
9581                        }
9582                    }
9583                    // File a report about this.
9584                    String msg = "System package " + pkg.packageName
9585                            + " signature changed; retaining data.";
9586                    reportSettingsProblem(Log.WARN, msg);
9587                }
9588            }
9589
9590            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9591                // This package wants to adopt ownership of permissions from
9592                // another package.
9593                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9594                    final String origName = pkg.mAdoptPermissions.get(i);
9595                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9596                    if (orig != null) {
9597                        if (verifyPackageUpdateLPr(orig, pkg)) {
9598                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9599                                    + pkg.packageName);
9600                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9601                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9602                        }
9603                    }
9604                }
9605            }
9606        }
9607
9608        pkg.applicationInfo.processName = fixProcessName(
9609                pkg.applicationInfo.packageName,
9610                pkg.applicationInfo.processName);
9611
9612        if (pkg != mPlatformPackage) {
9613            // Get all of our default paths setup
9614            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9615        }
9616
9617        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9618
9619        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9620            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9621                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9622                derivePackageAbi(
9623                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9624                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9625
9626                // Some system apps still use directory structure for native libraries
9627                // in which case we might end up not detecting abi solely based on apk
9628                // structure. Try to detect abi based on directory structure.
9629                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9630                        pkg.applicationInfo.primaryCpuAbi == null) {
9631                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9632                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9633                }
9634            } else {
9635                // This is not a first boot or an upgrade, don't bother deriving the
9636                // ABI during the scan. Instead, trust the value that was stored in the
9637                // package setting.
9638                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9639                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9640
9641                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9642
9643                if (DEBUG_ABI_SELECTION) {
9644                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9645                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9646                        pkg.applicationInfo.secondaryCpuAbi);
9647                }
9648            }
9649        } else {
9650            if ((scanFlags & SCAN_MOVE) != 0) {
9651                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9652                // but we already have this packages package info in the PackageSetting. We just
9653                // use that and derive the native library path based on the new codepath.
9654                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9655                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9656            }
9657
9658            // Set native library paths again. For moves, the path will be updated based on the
9659            // ABIs we've determined above. For non-moves, the path will be updated based on the
9660            // ABIs we determined during compilation, but the path will depend on the final
9661            // package path (after the rename away from the stage path).
9662            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9663        }
9664
9665        // This is a special case for the "system" package, where the ABI is
9666        // dictated by the zygote configuration (and init.rc). We should keep track
9667        // of this ABI so that we can deal with "normal" applications that run under
9668        // the same UID correctly.
9669        if (mPlatformPackage == pkg) {
9670            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9671                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9672        }
9673
9674        // If there's a mismatch between the abi-override in the package setting
9675        // and the abiOverride specified for the install. Warn about this because we
9676        // would've already compiled the app without taking the package setting into
9677        // account.
9678        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9679            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9680                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9681                        " for package " + pkg.packageName);
9682            }
9683        }
9684
9685        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9686        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9687        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9688
9689        // Copy the derived override back to the parsed package, so that we can
9690        // update the package settings accordingly.
9691        pkg.cpuAbiOverride = cpuAbiOverride;
9692
9693        if (DEBUG_ABI_SELECTION) {
9694            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9695                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9696                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9697        }
9698
9699        // Push the derived path down into PackageSettings so we know what to
9700        // clean up at uninstall time.
9701        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9702
9703        if (DEBUG_ABI_SELECTION) {
9704            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9705                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9706                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9707        }
9708
9709        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9710        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9711            // We don't do this here during boot because we can do it all
9712            // at once after scanning all existing packages.
9713            //
9714            // We also do this *before* we perform dexopt on this package, so that
9715            // we can avoid redundant dexopts, and also to make sure we've got the
9716            // code and package path correct.
9717            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9718        }
9719
9720        if (mFactoryTest && pkg.requestedPermissions.contains(
9721                android.Manifest.permission.FACTORY_TEST)) {
9722            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9723        }
9724
9725        if (isSystemApp(pkg)) {
9726            pkgSetting.isOrphaned = true;
9727        }
9728
9729        // Take care of first install / last update times.
9730        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9731        if (currentTime != 0) {
9732            if (pkgSetting.firstInstallTime == 0) {
9733                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9734            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9735                pkgSetting.lastUpdateTime = currentTime;
9736            }
9737        } else if (pkgSetting.firstInstallTime == 0) {
9738            // We need *something*.  Take time time stamp of the file.
9739            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9740        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9741            if (scanFileTime != pkgSetting.timeStamp) {
9742                // A package on the system image has changed; consider this
9743                // to be an update.
9744                pkgSetting.lastUpdateTime = scanFileTime;
9745            }
9746        }
9747        pkgSetting.setTimeStamp(scanFileTime);
9748
9749        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9750            if (nonMutatedPs != null) {
9751                synchronized (mPackages) {
9752                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9753                }
9754            }
9755        } else {
9756            final int userId = user == null ? 0 : user.getIdentifier();
9757            // Modify state for the given package setting
9758            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9759                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9760            if (pkgSetting.getInstantApp(userId)) {
9761                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9762            }
9763        }
9764        return pkg;
9765    }
9766
9767    /**
9768     * Applies policy to the parsed package based upon the given policy flags.
9769     * Ensures the package is in a good state.
9770     * <p>
9771     * Implementation detail: This method must NOT have any side effect. It would
9772     * ideally be static, but, it requires locks to read system state.
9773     */
9774    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9775        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9776            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9777            if (pkg.applicationInfo.isDirectBootAware()) {
9778                // we're direct boot aware; set for all components
9779                for (PackageParser.Service s : pkg.services) {
9780                    s.info.encryptionAware = s.info.directBootAware = true;
9781                }
9782                for (PackageParser.Provider p : pkg.providers) {
9783                    p.info.encryptionAware = p.info.directBootAware = true;
9784                }
9785                for (PackageParser.Activity a : pkg.activities) {
9786                    a.info.encryptionAware = a.info.directBootAware = true;
9787                }
9788                for (PackageParser.Activity r : pkg.receivers) {
9789                    r.info.encryptionAware = r.info.directBootAware = true;
9790                }
9791            }
9792        } else {
9793            // Only allow system apps to be flagged as core apps.
9794            pkg.coreApp = false;
9795            // clear flags not applicable to regular apps
9796            pkg.applicationInfo.privateFlags &=
9797                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9798            pkg.applicationInfo.privateFlags &=
9799                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9800        }
9801        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9802
9803        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9804            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9805        }
9806
9807        if (!isSystemApp(pkg)) {
9808            // Only system apps can use these features.
9809            pkg.mOriginalPackages = null;
9810            pkg.mRealPackage = null;
9811            pkg.mAdoptPermissions = null;
9812        }
9813    }
9814
9815    /**
9816     * Asserts the parsed package is valid according to the given policy. If the
9817     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9818     * <p>
9819     * Implementation detail: This method must NOT have any side effects. It would
9820     * ideally be static, but, it requires locks to read system state.
9821     *
9822     * @throws PackageManagerException If the package fails any of the validation checks
9823     */
9824    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9825            throws PackageManagerException {
9826        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9827            assertCodePolicy(pkg);
9828        }
9829
9830        if (pkg.applicationInfo.getCodePath() == null ||
9831                pkg.applicationInfo.getResourcePath() == null) {
9832            // Bail out. The resource and code paths haven't been set.
9833            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9834                    "Code and resource paths haven't been set correctly");
9835        }
9836
9837        // Make sure we're not adding any bogus keyset info
9838        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9839        ksms.assertScannedPackageValid(pkg);
9840
9841        synchronized (mPackages) {
9842            // The special "android" package can only be defined once
9843            if (pkg.packageName.equals("android")) {
9844                if (mAndroidApplication != null) {
9845                    Slog.w(TAG, "*************************************************");
9846                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9847                    Slog.w(TAG, " codePath=" + pkg.codePath);
9848                    Slog.w(TAG, "*************************************************");
9849                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9850                            "Core android package being redefined.  Skipping.");
9851                }
9852            }
9853
9854            // A package name must be unique; don't allow duplicates
9855            if (mPackages.containsKey(pkg.packageName)) {
9856                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9857                        "Application package " + pkg.packageName
9858                        + " already installed.  Skipping duplicate.");
9859            }
9860
9861            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9862                // Static libs have a synthetic package name containing the version
9863                // but we still want the base name to be unique.
9864                if (mPackages.containsKey(pkg.manifestPackageName)) {
9865                    throw new PackageManagerException(
9866                            "Duplicate static shared lib provider package");
9867                }
9868
9869                // Static shared libraries should have at least O target SDK
9870                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9871                    throw new PackageManagerException(
9872                            "Packages declaring static-shared libs must target O SDK or higher");
9873                }
9874
9875                // Package declaring static a shared lib cannot be instant apps
9876                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9877                    throw new PackageManagerException(
9878                            "Packages declaring static-shared libs cannot be instant apps");
9879                }
9880
9881                // Package declaring static a shared lib cannot be renamed since the package
9882                // name is synthetic and apps can't code around package manager internals.
9883                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9884                    throw new PackageManagerException(
9885                            "Packages declaring static-shared libs cannot be renamed");
9886                }
9887
9888                // Package declaring static a shared lib cannot declare child packages
9889                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9890                    throw new PackageManagerException(
9891                            "Packages declaring static-shared libs cannot have child packages");
9892                }
9893
9894                // Package declaring static a shared lib cannot declare dynamic libs
9895                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9896                    throw new PackageManagerException(
9897                            "Packages declaring static-shared libs cannot declare dynamic libs");
9898                }
9899
9900                // Package declaring static a shared lib cannot declare shared users
9901                if (pkg.mSharedUserId != null) {
9902                    throw new PackageManagerException(
9903                            "Packages declaring static-shared libs cannot declare shared users");
9904                }
9905
9906                // Static shared libs cannot declare activities
9907                if (!pkg.activities.isEmpty()) {
9908                    throw new PackageManagerException(
9909                            "Static shared libs cannot declare activities");
9910                }
9911
9912                // Static shared libs cannot declare services
9913                if (!pkg.services.isEmpty()) {
9914                    throw new PackageManagerException(
9915                            "Static shared libs cannot declare services");
9916                }
9917
9918                // Static shared libs cannot declare providers
9919                if (!pkg.providers.isEmpty()) {
9920                    throw new PackageManagerException(
9921                            "Static shared libs cannot declare content providers");
9922                }
9923
9924                // Static shared libs cannot declare receivers
9925                if (!pkg.receivers.isEmpty()) {
9926                    throw new PackageManagerException(
9927                            "Static shared libs cannot declare broadcast receivers");
9928                }
9929
9930                // Static shared libs cannot declare permission groups
9931                if (!pkg.permissionGroups.isEmpty()) {
9932                    throw new PackageManagerException(
9933                            "Static shared libs cannot declare permission groups");
9934                }
9935
9936                // Static shared libs cannot declare permissions
9937                if (!pkg.permissions.isEmpty()) {
9938                    throw new PackageManagerException(
9939                            "Static shared libs cannot declare permissions");
9940                }
9941
9942                // Static shared libs cannot declare protected broadcasts
9943                if (pkg.protectedBroadcasts != null) {
9944                    throw new PackageManagerException(
9945                            "Static shared libs cannot declare protected broadcasts");
9946                }
9947
9948                // Static shared libs cannot be overlay targets
9949                if (pkg.mOverlayTarget != null) {
9950                    throw new PackageManagerException(
9951                            "Static shared libs cannot be overlay targets");
9952                }
9953
9954                // The version codes must be ordered as lib versions
9955                int minVersionCode = Integer.MIN_VALUE;
9956                int maxVersionCode = Integer.MAX_VALUE;
9957
9958                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9959                        pkg.staticSharedLibName);
9960                if (versionedLib != null) {
9961                    final int versionCount = versionedLib.size();
9962                    for (int i = 0; i < versionCount; i++) {
9963                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9964                        // TODO: We will change version code to long, so in the new API it is long
9965                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9966                                .getVersionCode();
9967                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9968                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9969                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9970                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9971                        } else {
9972                            minVersionCode = maxVersionCode = libVersionCode;
9973                            break;
9974                        }
9975                    }
9976                }
9977                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9978                    throw new PackageManagerException("Static shared"
9979                            + " lib version codes must be ordered as lib versions");
9980                }
9981            }
9982
9983            // Only privileged apps and updated privileged apps can add child packages.
9984            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9985                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9986                    throw new PackageManagerException("Only privileged apps can add child "
9987                            + "packages. Ignoring package " + pkg.packageName);
9988                }
9989                final int childCount = pkg.childPackages.size();
9990                for (int i = 0; i < childCount; i++) {
9991                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9992                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9993                            childPkg.packageName)) {
9994                        throw new PackageManagerException("Can't override child of "
9995                                + "another disabled app. Ignoring package " + pkg.packageName);
9996                    }
9997                }
9998            }
9999
10000            // If we're only installing presumed-existing packages, require that the
10001            // scanned APK is both already known and at the path previously established
10002            // for it.  Previously unknown packages we pick up normally, but if we have an
10003            // a priori expectation about this package's install presence, enforce it.
10004            // With a singular exception for new system packages. When an OTA contains
10005            // a new system package, we allow the codepath to change from a system location
10006            // to the user-installed location. If we don't allow this change, any newer,
10007            // user-installed version of the application will be ignored.
10008            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10009                if (mExpectingBetter.containsKey(pkg.packageName)) {
10010                    logCriticalInfo(Log.WARN,
10011                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10012                } else {
10013                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10014                    if (known != null) {
10015                        if (DEBUG_PACKAGE_SCANNING) {
10016                            Log.d(TAG, "Examining " + pkg.codePath
10017                                    + " and requiring known paths " + known.codePathString
10018                                    + " & " + known.resourcePathString);
10019                        }
10020                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10021                                || !pkg.applicationInfo.getResourcePath().equals(
10022                                        known.resourcePathString)) {
10023                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10024                                    "Application package " + pkg.packageName
10025                                    + " found at " + pkg.applicationInfo.getCodePath()
10026                                    + " but expected at " + known.codePathString
10027                                    + "; ignoring.");
10028                        }
10029                    }
10030                }
10031            }
10032
10033            // Verify that this new package doesn't have any content providers
10034            // that conflict with existing packages.  Only do this if the
10035            // package isn't already installed, since we don't want to break
10036            // things that are installed.
10037            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10038                final int N = pkg.providers.size();
10039                int i;
10040                for (i=0; i<N; i++) {
10041                    PackageParser.Provider p = pkg.providers.get(i);
10042                    if (p.info.authority != null) {
10043                        String names[] = p.info.authority.split(";");
10044                        for (int j = 0; j < names.length; j++) {
10045                            if (mProvidersByAuthority.containsKey(names[j])) {
10046                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10047                                final String otherPackageName =
10048                                        ((other != null && other.getComponentName() != null) ?
10049                                                other.getComponentName().getPackageName() : "?");
10050                                throw new PackageManagerException(
10051                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10052                                        "Can't install because provider name " + names[j]
10053                                                + " (in package " + pkg.applicationInfo.packageName
10054                                                + ") is already used by " + otherPackageName);
10055                            }
10056                        }
10057                    }
10058                }
10059            }
10060        }
10061    }
10062
10063    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10064            int type, String declaringPackageName, int declaringVersionCode) {
10065        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10066        if (versionedLib == null) {
10067            versionedLib = new SparseArray<>();
10068            mSharedLibraries.put(name, versionedLib);
10069            if (type == SharedLibraryInfo.TYPE_STATIC) {
10070                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10071            }
10072        } else if (versionedLib.indexOfKey(version) >= 0) {
10073            return false;
10074        }
10075        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10076                version, type, declaringPackageName, declaringVersionCode);
10077        versionedLib.put(version, libEntry);
10078        return true;
10079    }
10080
10081    private boolean removeSharedLibraryLPw(String name, int version) {
10082        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10083        if (versionedLib == null) {
10084            return false;
10085        }
10086        final int libIdx = versionedLib.indexOfKey(version);
10087        if (libIdx < 0) {
10088            return false;
10089        }
10090        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10091        versionedLib.remove(version);
10092        if (versionedLib.size() <= 0) {
10093            mSharedLibraries.remove(name);
10094            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10095                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10096                        .getPackageName());
10097            }
10098        }
10099        return true;
10100    }
10101
10102    /**
10103     * Adds a scanned package to the system. When this method is finished, the package will
10104     * be available for query, resolution, etc...
10105     */
10106    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10107            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10108        final String pkgName = pkg.packageName;
10109        if (mCustomResolverComponentName != null &&
10110                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10111            setUpCustomResolverActivity(pkg);
10112        }
10113
10114        if (pkg.packageName.equals("android")) {
10115            synchronized (mPackages) {
10116                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10117                    // Set up information for our fall-back user intent resolution activity.
10118                    mPlatformPackage = pkg;
10119                    pkg.mVersionCode = mSdkVersion;
10120                    mAndroidApplication = pkg.applicationInfo;
10121                    if (!mResolverReplaced) {
10122                        mResolveActivity.applicationInfo = mAndroidApplication;
10123                        mResolveActivity.name = ResolverActivity.class.getName();
10124                        mResolveActivity.packageName = mAndroidApplication.packageName;
10125                        mResolveActivity.processName = "system:ui";
10126                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10127                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10128                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10129                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10130                        mResolveActivity.exported = true;
10131                        mResolveActivity.enabled = true;
10132                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10133                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10134                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10135                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10136                                | ActivityInfo.CONFIG_ORIENTATION
10137                                | ActivityInfo.CONFIG_KEYBOARD
10138                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10139                        mResolveInfo.activityInfo = mResolveActivity;
10140                        mResolveInfo.priority = 0;
10141                        mResolveInfo.preferredOrder = 0;
10142                        mResolveInfo.match = 0;
10143                        mResolveComponentName = new ComponentName(
10144                                mAndroidApplication.packageName, mResolveActivity.name);
10145                    }
10146                }
10147            }
10148        }
10149
10150        ArrayList<PackageParser.Package> clientLibPkgs = null;
10151        // writer
10152        synchronized (mPackages) {
10153            boolean hasStaticSharedLibs = false;
10154
10155            // Any app can add new static shared libraries
10156            if (pkg.staticSharedLibName != null) {
10157                // Static shared libs don't allow renaming as they have synthetic package
10158                // names to allow install of multiple versions, so use name from manifest.
10159                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10160                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10161                        pkg.manifestPackageName, pkg.mVersionCode)) {
10162                    hasStaticSharedLibs = true;
10163                } else {
10164                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10165                                + pkg.staticSharedLibName + " already exists; skipping");
10166                }
10167                // Static shared libs cannot be updated once installed since they
10168                // use synthetic package name which includes the version code, so
10169                // not need to update other packages's shared lib dependencies.
10170            }
10171
10172            if (!hasStaticSharedLibs
10173                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10174                // Only system apps can add new dynamic shared libraries.
10175                if (pkg.libraryNames != null) {
10176                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10177                        String name = pkg.libraryNames.get(i);
10178                        boolean allowed = false;
10179                        if (pkg.isUpdatedSystemApp()) {
10180                            // New library entries can only be added through the
10181                            // system image.  This is important to get rid of a lot
10182                            // of nasty edge cases: for example if we allowed a non-
10183                            // system update of the app to add a library, then uninstalling
10184                            // the update would make the library go away, and assumptions
10185                            // we made such as through app install filtering would now
10186                            // have allowed apps on the device which aren't compatible
10187                            // with it.  Better to just have the restriction here, be
10188                            // conservative, and create many fewer cases that can negatively
10189                            // impact the user experience.
10190                            final PackageSetting sysPs = mSettings
10191                                    .getDisabledSystemPkgLPr(pkg.packageName);
10192                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10193                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10194                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10195                                        allowed = true;
10196                                        break;
10197                                    }
10198                                }
10199                            }
10200                        } else {
10201                            allowed = true;
10202                        }
10203                        if (allowed) {
10204                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10205                                    SharedLibraryInfo.VERSION_UNDEFINED,
10206                                    SharedLibraryInfo.TYPE_DYNAMIC,
10207                                    pkg.packageName, pkg.mVersionCode)) {
10208                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10209                                        + name + " already exists; skipping");
10210                            }
10211                        } else {
10212                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10213                                    + name + " that is not declared on system image; skipping");
10214                        }
10215                    }
10216
10217                    if ((scanFlags & SCAN_BOOTING) == 0) {
10218                        // If we are not booting, we need to update any applications
10219                        // that are clients of our shared library.  If we are booting,
10220                        // this will all be done once the scan is complete.
10221                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10222                    }
10223                }
10224            }
10225        }
10226
10227        if ((scanFlags & SCAN_BOOTING) != 0) {
10228            // No apps can run during boot scan, so they don't need to be frozen
10229        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10230            // Caller asked to not kill app, so it's probably not frozen
10231        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10232            // Caller asked us to ignore frozen check for some reason; they
10233            // probably didn't know the package name
10234        } else {
10235            // We're doing major surgery on this package, so it better be frozen
10236            // right now to keep it from launching
10237            checkPackageFrozen(pkgName);
10238        }
10239
10240        // Also need to kill any apps that are dependent on the library.
10241        if (clientLibPkgs != null) {
10242            for (int i=0; i<clientLibPkgs.size(); i++) {
10243                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10244                killApplication(clientPkg.applicationInfo.packageName,
10245                        clientPkg.applicationInfo.uid, "update lib");
10246            }
10247        }
10248
10249        // writer
10250        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10251
10252        synchronized (mPackages) {
10253            // We don't expect installation to fail beyond this point
10254
10255            // Add the new setting to mSettings
10256            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10257            // Add the new setting to mPackages
10258            mPackages.put(pkg.applicationInfo.packageName, pkg);
10259            // Make sure we don't accidentally delete its data.
10260            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10261            while (iter.hasNext()) {
10262                PackageCleanItem item = iter.next();
10263                if (pkgName.equals(item.packageName)) {
10264                    iter.remove();
10265                }
10266            }
10267
10268            // Add the package's KeySets to the global KeySetManagerService
10269            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10270            ksms.addScannedPackageLPw(pkg);
10271
10272            int N = pkg.providers.size();
10273            StringBuilder r = null;
10274            int i;
10275            for (i=0; i<N; i++) {
10276                PackageParser.Provider p = pkg.providers.get(i);
10277                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10278                        p.info.processName);
10279                mProviders.addProvider(p);
10280                p.syncable = p.info.isSyncable;
10281                if (p.info.authority != null) {
10282                    String names[] = p.info.authority.split(";");
10283                    p.info.authority = null;
10284                    for (int j = 0; j < names.length; j++) {
10285                        if (j == 1 && p.syncable) {
10286                            // We only want the first authority for a provider to possibly be
10287                            // syncable, so if we already added this provider using a different
10288                            // authority clear the syncable flag. We copy the provider before
10289                            // changing it because the mProviders object contains a reference
10290                            // to a provider that we don't want to change.
10291                            // Only do this for the second authority since the resulting provider
10292                            // object can be the same for all future authorities for this provider.
10293                            p = new PackageParser.Provider(p);
10294                            p.syncable = false;
10295                        }
10296                        if (!mProvidersByAuthority.containsKey(names[j])) {
10297                            mProvidersByAuthority.put(names[j], p);
10298                            if (p.info.authority == null) {
10299                                p.info.authority = names[j];
10300                            } else {
10301                                p.info.authority = p.info.authority + ";" + names[j];
10302                            }
10303                            if (DEBUG_PACKAGE_SCANNING) {
10304                                if (chatty)
10305                                    Log.d(TAG, "Registered content provider: " + names[j]
10306                                            + ", className = " + p.info.name + ", isSyncable = "
10307                                            + p.info.isSyncable);
10308                            }
10309                        } else {
10310                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10311                            Slog.w(TAG, "Skipping provider name " + names[j] +
10312                                    " (in package " + pkg.applicationInfo.packageName +
10313                                    "): name already used by "
10314                                    + ((other != null && other.getComponentName() != null)
10315                                            ? other.getComponentName().getPackageName() : "?"));
10316                        }
10317                    }
10318                }
10319                if (chatty) {
10320                    if (r == null) {
10321                        r = new StringBuilder(256);
10322                    } else {
10323                        r.append(' ');
10324                    }
10325                    r.append(p.info.name);
10326                }
10327            }
10328            if (r != null) {
10329                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10330            }
10331
10332            N = pkg.services.size();
10333            r = null;
10334            for (i=0; i<N; i++) {
10335                PackageParser.Service s = pkg.services.get(i);
10336                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10337                        s.info.processName);
10338                mServices.addService(s);
10339                if (chatty) {
10340                    if (r == null) {
10341                        r = new StringBuilder(256);
10342                    } else {
10343                        r.append(' ');
10344                    }
10345                    r.append(s.info.name);
10346                }
10347            }
10348            if (r != null) {
10349                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10350            }
10351
10352            N = pkg.receivers.size();
10353            r = null;
10354            for (i=0; i<N; i++) {
10355                PackageParser.Activity a = pkg.receivers.get(i);
10356                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10357                        a.info.processName);
10358                mReceivers.addActivity(a, "receiver");
10359                if (chatty) {
10360                    if (r == null) {
10361                        r = new StringBuilder(256);
10362                    } else {
10363                        r.append(' ');
10364                    }
10365                    r.append(a.info.name);
10366                }
10367            }
10368            if (r != null) {
10369                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10370            }
10371
10372            N = pkg.activities.size();
10373            r = null;
10374            for (i=0; i<N; i++) {
10375                PackageParser.Activity a = pkg.activities.get(i);
10376                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10377                        a.info.processName);
10378                mActivities.addActivity(a, "activity");
10379                if (chatty) {
10380                    if (r == null) {
10381                        r = new StringBuilder(256);
10382                    } else {
10383                        r.append(' ');
10384                    }
10385                    r.append(a.info.name);
10386                }
10387            }
10388            if (r != null) {
10389                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10390            }
10391
10392            N = pkg.permissionGroups.size();
10393            r = null;
10394            for (i=0; i<N; i++) {
10395                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10396                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10397                final String curPackageName = cur == null ? null : cur.info.packageName;
10398                // Dont allow ephemeral apps to define new permission groups.
10399                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10400                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10401                            + pg.info.packageName
10402                            + " ignored: instant apps cannot define new permission groups.");
10403                    continue;
10404                }
10405                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10406                if (cur == null || isPackageUpdate) {
10407                    mPermissionGroups.put(pg.info.name, pg);
10408                    if (chatty) {
10409                        if (r == null) {
10410                            r = new StringBuilder(256);
10411                        } else {
10412                            r.append(' ');
10413                        }
10414                        if (isPackageUpdate) {
10415                            r.append("UPD:");
10416                        }
10417                        r.append(pg.info.name);
10418                    }
10419                } else {
10420                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10421                            + pg.info.packageName + " ignored: original from "
10422                            + cur.info.packageName);
10423                    if (chatty) {
10424                        if (r == null) {
10425                            r = new StringBuilder(256);
10426                        } else {
10427                            r.append(' ');
10428                        }
10429                        r.append("DUP:");
10430                        r.append(pg.info.name);
10431                    }
10432                }
10433            }
10434            if (r != null) {
10435                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10436            }
10437
10438            N = pkg.permissions.size();
10439            r = null;
10440            for (i=0; i<N; i++) {
10441                PackageParser.Permission p = pkg.permissions.get(i);
10442
10443                // Dont allow ephemeral apps to define new permissions.
10444                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10445                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10446                            + p.info.packageName
10447                            + " ignored: instant apps cannot define new permissions.");
10448                    continue;
10449                }
10450
10451                // Assume by default that we did not install this permission into the system.
10452                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10453
10454                // Now that permission groups have a special meaning, we ignore permission
10455                // groups for legacy apps to prevent unexpected behavior. In particular,
10456                // permissions for one app being granted to someone just becase they happen
10457                // to be in a group defined by another app (before this had no implications).
10458                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10459                    p.group = mPermissionGroups.get(p.info.group);
10460                    // Warn for a permission in an unknown group.
10461                    if (p.info.group != null && p.group == null) {
10462                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10463                                + p.info.packageName + " in an unknown group " + p.info.group);
10464                    }
10465                }
10466
10467                ArrayMap<String, BasePermission> permissionMap =
10468                        p.tree ? mSettings.mPermissionTrees
10469                                : mSettings.mPermissions;
10470                BasePermission bp = permissionMap.get(p.info.name);
10471
10472                // Allow system apps to redefine non-system permissions
10473                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10474                    final boolean currentOwnerIsSystem = (bp.perm != null
10475                            && isSystemApp(bp.perm.owner));
10476                    if (isSystemApp(p.owner)) {
10477                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10478                            // It's a built-in permission and no owner, take ownership now
10479                            bp.packageSetting = pkgSetting;
10480                            bp.perm = p;
10481                            bp.uid = pkg.applicationInfo.uid;
10482                            bp.sourcePackage = p.info.packageName;
10483                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10484                        } else if (!currentOwnerIsSystem) {
10485                            String msg = "New decl " + p.owner + " of permission  "
10486                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10487                            reportSettingsProblem(Log.WARN, msg);
10488                            bp = null;
10489                        }
10490                    }
10491                }
10492
10493                if (bp == null) {
10494                    bp = new BasePermission(p.info.name, p.info.packageName,
10495                            BasePermission.TYPE_NORMAL);
10496                    permissionMap.put(p.info.name, bp);
10497                }
10498
10499                if (bp.perm == null) {
10500                    if (bp.sourcePackage == null
10501                            || bp.sourcePackage.equals(p.info.packageName)) {
10502                        BasePermission tree = findPermissionTreeLP(p.info.name);
10503                        if (tree == null
10504                                || tree.sourcePackage.equals(p.info.packageName)) {
10505                            bp.packageSetting = pkgSetting;
10506                            bp.perm = p;
10507                            bp.uid = pkg.applicationInfo.uid;
10508                            bp.sourcePackage = p.info.packageName;
10509                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10510                            if (chatty) {
10511                                if (r == null) {
10512                                    r = new StringBuilder(256);
10513                                } else {
10514                                    r.append(' ');
10515                                }
10516                                r.append(p.info.name);
10517                            }
10518                        } else {
10519                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10520                                    + p.info.packageName + " ignored: base tree "
10521                                    + tree.name + " is from package "
10522                                    + tree.sourcePackage);
10523                        }
10524                    } else {
10525                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10526                                + p.info.packageName + " ignored: original from "
10527                                + bp.sourcePackage);
10528                    }
10529                } else if (chatty) {
10530                    if (r == null) {
10531                        r = new StringBuilder(256);
10532                    } else {
10533                        r.append(' ');
10534                    }
10535                    r.append("DUP:");
10536                    r.append(p.info.name);
10537                }
10538                if (bp.perm == p) {
10539                    bp.protectionLevel = p.info.protectionLevel;
10540                }
10541            }
10542
10543            if (r != null) {
10544                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10545            }
10546
10547            N = pkg.instrumentation.size();
10548            r = null;
10549            for (i=0; i<N; i++) {
10550                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10551                a.info.packageName = pkg.applicationInfo.packageName;
10552                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10553                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10554                a.info.splitNames = pkg.splitNames;
10555                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10556                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10557                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10558                a.info.dataDir = pkg.applicationInfo.dataDir;
10559                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10560                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10561                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10562                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10563                mInstrumentation.put(a.getComponentName(), a);
10564                if (chatty) {
10565                    if (r == null) {
10566                        r = new StringBuilder(256);
10567                    } else {
10568                        r.append(' ');
10569                    }
10570                    r.append(a.info.name);
10571                }
10572            }
10573            if (r != null) {
10574                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10575            }
10576
10577            if (pkg.protectedBroadcasts != null) {
10578                N = pkg.protectedBroadcasts.size();
10579                for (i=0; i<N; i++) {
10580                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10581                }
10582            }
10583        }
10584
10585        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10586    }
10587
10588    /**
10589     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10590     * is derived purely on the basis of the contents of {@code scanFile} and
10591     * {@code cpuAbiOverride}.
10592     *
10593     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10594     */
10595    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10596                                 String cpuAbiOverride, boolean extractLibs,
10597                                 File appLib32InstallDir)
10598            throws PackageManagerException {
10599        // Give ourselves some initial paths; we'll come back for another
10600        // pass once we've determined ABI below.
10601        setNativeLibraryPaths(pkg, appLib32InstallDir);
10602
10603        // We would never need to extract libs for forward-locked and external packages,
10604        // since the container service will do it for us. We shouldn't attempt to
10605        // extract libs from system app when it was not updated.
10606        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10607                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10608            extractLibs = false;
10609        }
10610
10611        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10612        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10613
10614        NativeLibraryHelper.Handle handle = null;
10615        try {
10616            handle = NativeLibraryHelper.Handle.create(pkg);
10617            // TODO(multiArch): This can be null for apps that didn't go through the
10618            // usual installation process. We can calculate it again, like we
10619            // do during install time.
10620            //
10621            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10622            // unnecessary.
10623            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10624
10625            // Null out the abis so that they can be recalculated.
10626            pkg.applicationInfo.primaryCpuAbi = null;
10627            pkg.applicationInfo.secondaryCpuAbi = null;
10628            if (isMultiArch(pkg.applicationInfo)) {
10629                // Warn if we've set an abiOverride for multi-lib packages..
10630                // By definition, we need to copy both 32 and 64 bit libraries for
10631                // such packages.
10632                if (pkg.cpuAbiOverride != null
10633                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10634                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10635                }
10636
10637                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10638                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10639                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10640                    if (extractLibs) {
10641                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10642                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10643                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10644                                useIsaSpecificSubdirs);
10645                    } else {
10646                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10647                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10648                    }
10649                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10650                }
10651
10652                maybeThrowExceptionForMultiArchCopy(
10653                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10654
10655                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10656                    if (extractLibs) {
10657                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10658                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10659                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10660                                useIsaSpecificSubdirs);
10661                    } else {
10662                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10663                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10664                    }
10665                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10666                }
10667
10668                maybeThrowExceptionForMultiArchCopy(
10669                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10670
10671                if (abi64 >= 0) {
10672                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10673                }
10674
10675                if (abi32 >= 0) {
10676                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10677                    if (abi64 >= 0) {
10678                        if (pkg.use32bitAbi) {
10679                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10680                            pkg.applicationInfo.primaryCpuAbi = abi;
10681                        } else {
10682                            pkg.applicationInfo.secondaryCpuAbi = abi;
10683                        }
10684                    } else {
10685                        pkg.applicationInfo.primaryCpuAbi = abi;
10686                    }
10687                }
10688
10689            } else {
10690                String[] abiList = (cpuAbiOverride != null) ?
10691                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10692
10693                // Enable gross and lame hacks for apps that are built with old
10694                // SDK tools. We must scan their APKs for renderscript bitcode and
10695                // not launch them if it's present. Don't bother checking on devices
10696                // that don't have 64 bit support.
10697                boolean needsRenderScriptOverride = false;
10698                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10699                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10700                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10701                    needsRenderScriptOverride = true;
10702                }
10703
10704                final int copyRet;
10705                if (extractLibs) {
10706                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10707                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10708                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10709                } else {
10710                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10711                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10712                }
10713                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10714
10715                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10716                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10717                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10718                }
10719
10720                if (copyRet >= 0) {
10721                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10722                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10723                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10724                } else if (needsRenderScriptOverride) {
10725                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10726                }
10727            }
10728        } catch (IOException ioe) {
10729            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10730        } finally {
10731            IoUtils.closeQuietly(handle);
10732        }
10733
10734        // Now that we've calculated the ABIs and determined if it's an internal app,
10735        // we will go ahead and populate the nativeLibraryPath.
10736        setNativeLibraryPaths(pkg, appLib32InstallDir);
10737    }
10738
10739    /**
10740     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10741     * i.e, so that all packages can be run inside a single process if required.
10742     *
10743     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10744     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10745     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10746     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10747     * updating a package that belongs to a shared user.
10748     *
10749     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10750     * adds unnecessary complexity.
10751     */
10752    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10753            PackageParser.Package scannedPackage) {
10754        String requiredInstructionSet = null;
10755        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10756            requiredInstructionSet = VMRuntime.getInstructionSet(
10757                     scannedPackage.applicationInfo.primaryCpuAbi);
10758        }
10759
10760        PackageSetting requirer = null;
10761        for (PackageSetting ps : packagesForUser) {
10762            // If packagesForUser contains scannedPackage, we skip it. This will happen
10763            // when scannedPackage is an update of an existing package. Without this check,
10764            // we will never be able to change the ABI of any package belonging to a shared
10765            // user, even if it's compatible with other packages.
10766            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10767                if (ps.primaryCpuAbiString == null) {
10768                    continue;
10769                }
10770
10771                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10772                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10773                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10774                    // this but there's not much we can do.
10775                    String errorMessage = "Instruction set mismatch, "
10776                            + ((requirer == null) ? "[caller]" : requirer)
10777                            + " requires " + requiredInstructionSet + " whereas " + ps
10778                            + " requires " + instructionSet;
10779                    Slog.w(TAG, errorMessage);
10780                }
10781
10782                if (requiredInstructionSet == null) {
10783                    requiredInstructionSet = instructionSet;
10784                    requirer = ps;
10785                }
10786            }
10787        }
10788
10789        if (requiredInstructionSet != null) {
10790            String adjustedAbi;
10791            if (requirer != null) {
10792                // requirer != null implies that either scannedPackage was null or that scannedPackage
10793                // did not require an ABI, in which case we have to adjust scannedPackage to match
10794                // the ABI of the set (which is the same as requirer's ABI)
10795                adjustedAbi = requirer.primaryCpuAbiString;
10796                if (scannedPackage != null) {
10797                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10798                }
10799            } else {
10800                // requirer == null implies that we're updating all ABIs in the set to
10801                // match scannedPackage.
10802                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10803            }
10804
10805            for (PackageSetting ps : packagesForUser) {
10806                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10807                    if (ps.primaryCpuAbiString != null) {
10808                        continue;
10809                    }
10810
10811                    ps.primaryCpuAbiString = adjustedAbi;
10812                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10813                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10814                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10815                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10816                                + " (requirer="
10817                                + (requirer != null ? requirer.pkg : "null")
10818                                + ", scannedPackage="
10819                                + (scannedPackage != null ? scannedPackage : "null")
10820                                + ")");
10821                        try {
10822                            mInstaller.rmdex(ps.codePathString,
10823                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10824                        } catch (InstallerException ignored) {
10825                        }
10826                    }
10827                }
10828            }
10829        }
10830    }
10831
10832    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10833        synchronized (mPackages) {
10834            mResolverReplaced = true;
10835            // Set up information for custom user intent resolution activity.
10836            mResolveActivity.applicationInfo = pkg.applicationInfo;
10837            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10838            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10839            mResolveActivity.processName = pkg.applicationInfo.packageName;
10840            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10841            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10842                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10843            mResolveActivity.theme = 0;
10844            mResolveActivity.exported = true;
10845            mResolveActivity.enabled = true;
10846            mResolveInfo.activityInfo = mResolveActivity;
10847            mResolveInfo.priority = 0;
10848            mResolveInfo.preferredOrder = 0;
10849            mResolveInfo.match = 0;
10850            mResolveComponentName = mCustomResolverComponentName;
10851            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10852                    mResolveComponentName);
10853        }
10854    }
10855
10856    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10857        if (installerActivity == null) {
10858            if (DEBUG_EPHEMERAL) {
10859                Slog.d(TAG, "Clear ephemeral installer activity");
10860            }
10861            mInstantAppInstallerActivity = null;
10862            return;
10863        }
10864
10865        if (DEBUG_EPHEMERAL) {
10866            Slog.d(TAG, "Set ephemeral installer activity: "
10867                    + installerActivity.getComponentName());
10868        }
10869        // Set up information for ephemeral installer activity
10870        mInstantAppInstallerActivity = installerActivity;
10871        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10872                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10873        mInstantAppInstallerActivity.exported = true;
10874        mInstantAppInstallerActivity.enabled = true;
10875        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10876        mInstantAppInstallerInfo.priority = 0;
10877        mInstantAppInstallerInfo.preferredOrder = 1;
10878        mInstantAppInstallerInfo.isDefault = true;
10879        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10880                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10881    }
10882
10883    private static String calculateBundledApkRoot(final String codePathString) {
10884        final File codePath = new File(codePathString);
10885        final File codeRoot;
10886        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10887            codeRoot = Environment.getRootDirectory();
10888        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10889            codeRoot = Environment.getOemDirectory();
10890        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10891            codeRoot = Environment.getVendorDirectory();
10892        } else {
10893            // Unrecognized code path; take its top real segment as the apk root:
10894            // e.g. /something/app/blah.apk => /something
10895            try {
10896                File f = codePath.getCanonicalFile();
10897                File parent = f.getParentFile();    // non-null because codePath is a file
10898                File tmp;
10899                while ((tmp = parent.getParentFile()) != null) {
10900                    f = parent;
10901                    parent = tmp;
10902                }
10903                codeRoot = f;
10904                Slog.w(TAG, "Unrecognized code path "
10905                        + codePath + " - using " + codeRoot);
10906            } catch (IOException e) {
10907                // Can't canonicalize the code path -- shenanigans?
10908                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10909                return Environment.getRootDirectory().getPath();
10910            }
10911        }
10912        return codeRoot.getPath();
10913    }
10914
10915    /**
10916     * Derive and set the location of native libraries for the given package,
10917     * which varies depending on where and how the package was installed.
10918     */
10919    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10920        final ApplicationInfo info = pkg.applicationInfo;
10921        final String codePath = pkg.codePath;
10922        final File codeFile = new File(codePath);
10923        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10924        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10925
10926        info.nativeLibraryRootDir = null;
10927        info.nativeLibraryRootRequiresIsa = false;
10928        info.nativeLibraryDir = null;
10929        info.secondaryNativeLibraryDir = null;
10930
10931        if (isApkFile(codeFile)) {
10932            // Monolithic install
10933            if (bundledApp) {
10934                // If "/system/lib64/apkname" exists, assume that is the per-package
10935                // native library directory to use; otherwise use "/system/lib/apkname".
10936                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10937                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10938                        getPrimaryInstructionSet(info));
10939
10940                // This is a bundled system app so choose the path based on the ABI.
10941                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10942                // is just the default path.
10943                final String apkName = deriveCodePathName(codePath);
10944                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10945                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10946                        apkName).getAbsolutePath();
10947
10948                if (info.secondaryCpuAbi != null) {
10949                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10950                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10951                            secondaryLibDir, apkName).getAbsolutePath();
10952                }
10953            } else if (asecApp) {
10954                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10955                        .getAbsolutePath();
10956            } else {
10957                final String apkName = deriveCodePathName(codePath);
10958                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10959                        .getAbsolutePath();
10960            }
10961
10962            info.nativeLibraryRootRequiresIsa = false;
10963            info.nativeLibraryDir = info.nativeLibraryRootDir;
10964        } else {
10965            // Cluster install
10966            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10967            info.nativeLibraryRootRequiresIsa = true;
10968
10969            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10970                    getPrimaryInstructionSet(info)).getAbsolutePath();
10971
10972            if (info.secondaryCpuAbi != null) {
10973                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10974                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10975            }
10976        }
10977    }
10978
10979    /**
10980     * Calculate the abis and roots for a bundled app. These can uniquely
10981     * be determined from the contents of the system partition, i.e whether
10982     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10983     * of this information, and instead assume that the system was built
10984     * sensibly.
10985     */
10986    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10987                                           PackageSetting pkgSetting) {
10988        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10989
10990        // If "/system/lib64/apkname" exists, assume that is the per-package
10991        // native library directory to use; otherwise use "/system/lib/apkname".
10992        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10993        setBundledAppAbi(pkg, apkRoot, apkName);
10994        // pkgSetting might be null during rescan following uninstall of updates
10995        // to a bundled app, so accommodate that possibility.  The settings in
10996        // that case will be established later from the parsed package.
10997        //
10998        // If the settings aren't null, sync them up with what we've just derived.
10999        // note that apkRoot isn't stored in the package settings.
11000        if (pkgSetting != null) {
11001            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11002            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11003        }
11004    }
11005
11006    /**
11007     * Deduces the ABI of a bundled app and sets the relevant fields on the
11008     * parsed pkg object.
11009     *
11010     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11011     *        under which system libraries are installed.
11012     * @param apkName the name of the installed package.
11013     */
11014    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11015        final File codeFile = new File(pkg.codePath);
11016
11017        final boolean has64BitLibs;
11018        final boolean has32BitLibs;
11019        if (isApkFile(codeFile)) {
11020            // Monolithic install
11021            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11022            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11023        } else {
11024            // Cluster install
11025            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11026            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11027                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11028                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11029                has64BitLibs = (new File(rootDir, isa)).exists();
11030            } else {
11031                has64BitLibs = false;
11032            }
11033            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11034                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11035                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11036                has32BitLibs = (new File(rootDir, isa)).exists();
11037            } else {
11038                has32BitLibs = false;
11039            }
11040        }
11041
11042        if (has64BitLibs && !has32BitLibs) {
11043            // The package has 64 bit libs, but not 32 bit libs. Its primary
11044            // ABI should be 64 bit. We can safely assume here that the bundled
11045            // native libraries correspond to the most preferred ABI in the list.
11046
11047            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11048            pkg.applicationInfo.secondaryCpuAbi = null;
11049        } else if (has32BitLibs && !has64BitLibs) {
11050            // The package has 32 bit libs but not 64 bit libs. Its primary
11051            // ABI should be 32 bit.
11052
11053            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11054            pkg.applicationInfo.secondaryCpuAbi = null;
11055        } else if (has32BitLibs && has64BitLibs) {
11056            // The application has both 64 and 32 bit bundled libraries. We check
11057            // here that the app declares multiArch support, and warn if it doesn't.
11058            //
11059            // We will be lenient here and record both ABIs. The primary will be the
11060            // ABI that's higher on the list, i.e, a device that's configured to prefer
11061            // 64 bit apps will see a 64 bit primary ABI,
11062
11063            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11064                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11065            }
11066
11067            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11068                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11069                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11070            } else {
11071                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11072                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11073            }
11074        } else {
11075            pkg.applicationInfo.primaryCpuAbi = null;
11076            pkg.applicationInfo.secondaryCpuAbi = null;
11077        }
11078    }
11079
11080    private void killApplication(String pkgName, int appId, String reason) {
11081        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11082    }
11083
11084    private void killApplication(String pkgName, int appId, int userId, String reason) {
11085        // Request the ActivityManager to kill the process(only for existing packages)
11086        // so that we do not end up in a confused state while the user is still using the older
11087        // version of the application while the new one gets installed.
11088        final long token = Binder.clearCallingIdentity();
11089        try {
11090            IActivityManager am = ActivityManager.getService();
11091            if (am != null) {
11092                try {
11093                    am.killApplication(pkgName, appId, userId, reason);
11094                } catch (RemoteException e) {
11095                }
11096            }
11097        } finally {
11098            Binder.restoreCallingIdentity(token);
11099        }
11100    }
11101
11102    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11103        // Remove the parent package setting
11104        PackageSetting ps = (PackageSetting) pkg.mExtras;
11105        if (ps != null) {
11106            removePackageLI(ps, chatty);
11107        }
11108        // Remove the child package setting
11109        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11110        for (int i = 0; i < childCount; i++) {
11111            PackageParser.Package childPkg = pkg.childPackages.get(i);
11112            ps = (PackageSetting) childPkg.mExtras;
11113            if (ps != null) {
11114                removePackageLI(ps, chatty);
11115            }
11116        }
11117    }
11118
11119    void removePackageLI(PackageSetting ps, boolean chatty) {
11120        if (DEBUG_INSTALL) {
11121            if (chatty)
11122                Log.d(TAG, "Removing package " + ps.name);
11123        }
11124
11125        // writer
11126        synchronized (mPackages) {
11127            mPackages.remove(ps.name);
11128            final PackageParser.Package pkg = ps.pkg;
11129            if (pkg != null) {
11130                cleanPackageDataStructuresLILPw(pkg, chatty);
11131            }
11132        }
11133    }
11134
11135    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11136        if (DEBUG_INSTALL) {
11137            if (chatty)
11138                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11139        }
11140
11141        // writer
11142        synchronized (mPackages) {
11143            // Remove the parent package
11144            mPackages.remove(pkg.applicationInfo.packageName);
11145            cleanPackageDataStructuresLILPw(pkg, chatty);
11146
11147            // Remove the child packages
11148            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11149            for (int i = 0; i < childCount; i++) {
11150                PackageParser.Package childPkg = pkg.childPackages.get(i);
11151                mPackages.remove(childPkg.applicationInfo.packageName);
11152                cleanPackageDataStructuresLILPw(childPkg, chatty);
11153            }
11154        }
11155    }
11156
11157    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11158        int N = pkg.providers.size();
11159        StringBuilder r = null;
11160        int i;
11161        for (i=0; i<N; i++) {
11162            PackageParser.Provider p = pkg.providers.get(i);
11163            mProviders.removeProvider(p);
11164            if (p.info.authority == null) {
11165
11166                /* There was another ContentProvider with this authority when
11167                 * this app was installed so this authority is null,
11168                 * Ignore it as we don't have to unregister the provider.
11169                 */
11170                continue;
11171            }
11172            String names[] = p.info.authority.split(";");
11173            for (int j = 0; j < names.length; j++) {
11174                if (mProvidersByAuthority.get(names[j]) == p) {
11175                    mProvidersByAuthority.remove(names[j]);
11176                    if (DEBUG_REMOVE) {
11177                        if (chatty)
11178                            Log.d(TAG, "Unregistered content provider: " + names[j]
11179                                    + ", className = " + p.info.name + ", isSyncable = "
11180                                    + p.info.isSyncable);
11181                    }
11182                }
11183            }
11184            if (DEBUG_REMOVE && chatty) {
11185                if (r == null) {
11186                    r = new StringBuilder(256);
11187                } else {
11188                    r.append(' ');
11189                }
11190                r.append(p.info.name);
11191            }
11192        }
11193        if (r != null) {
11194            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11195        }
11196
11197        N = pkg.services.size();
11198        r = null;
11199        for (i=0; i<N; i++) {
11200            PackageParser.Service s = pkg.services.get(i);
11201            mServices.removeService(s);
11202            if (chatty) {
11203                if (r == null) {
11204                    r = new StringBuilder(256);
11205                } else {
11206                    r.append(' ');
11207                }
11208                r.append(s.info.name);
11209            }
11210        }
11211        if (r != null) {
11212            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11213        }
11214
11215        N = pkg.receivers.size();
11216        r = null;
11217        for (i=0; i<N; i++) {
11218            PackageParser.Activity a = pkg.receivers.get(i);
11219            mReceivers.removeActivity(a, "receiver");
11220            if (DEBUG_REMOVE && chatty) {
11221                if (r == null) {
11222                    r = new StringBuilder(256);
11223                } else {
11224                    r.append(' ');
11225                }
11226                r.append(a.info.name);
11227            }
11228        }
11229        if (r != null) {
11230            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11231        }
11232
11233        N = pkg.activities.size();
11234        r = null;
11235        for (i=0; i<N; i++) {
11236            PackageParser.Activity a = pkg.activities.get(i);
11237            mActivities.removeActivity(a, "activity");
11238            if (DEBUG_REMOVE && chatty) {
11239                if (r == null) {
11240                    r = new StringBuilder(256);
11241                } else {
11242                    r.append(' ');
11243                }
11244                r.append(a.info.name);
11245            }
11246        }
11247        if (r != null) {
11248            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11249        }
11250
11251        N = pkg.permissions.size();
11252        r = null;
11253        for (i=0; i<N; i++) {
11254            PackageParser.Permission p = pkg.permissions.get(i);
11255            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11256            if (bp == null) {
11257                bp = mSettings.mPermissionTrees.get(p.info.name);
11258            }
11259            if (bp != null && bp.perm == p) {
11260                bp.perm = null;
11261                if (DEBUG_REMOVE && chatty) {
11262                    if (r == null) {
11263                        r = new StringBuilder(256);
11264                    } else {
11265                        r.append(' ');
11266                    }
11267                    r.append(p.info.name);
11268                }
11269            }
11270            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11271                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11272                if (appOpPkgs != null) {
11273                    appOpPkgs.remove(pkg.packageName);
11274                }
11275            }
11276        }
11277        if (r != null) {
11278            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11279        }
11280
11281        N = pkg.requestedPermissions.size();
11282        r = null;
11283        for (i=0; i<N; i++) {
11284            String perm = pkg.requestedPermissions.get(i);
11285            BasePermission bp = mSettings.mPermissions.get(perm);
11286            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11287                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11288                if (appOpPkgs != null) {
11289                    appOpPkgs.remove(pkg.packageName);
11290                    if (appOpPkgs.isEmpty()) {
11291                        mAppOpPermissionPackages.remove(perm);
11292                    }
11293                }
11294            }
11295        }
11296        if (r != null) {
11297            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11298        }
11299
11300        N = pkg.instrumentation.size();
11301        r = null;
11302        for (i=0; i<N; i++) {
11303            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11304            mInstrumentation.remove(a.getComponentName());
11305            if (DEBUG_REMOVE && chatty) {
11306                if (r == null) {
11307                    r = new StringBuilder(256);
11308                } else {
11309                    r.append(' ');
11310                }
11311                r.append(a.info.name);
11312            }
11313        }
11314        if (r != null) {
11315            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11316        }
11317
11318        r = null;
11319        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11320            // Only system apps can hold shared libraries.
11321            if (pkg.libraryNames != null) {
11322                for (i = 0; i < pkg.libraryNames.size(); i++) {
11323                    String name = pkg.libraryNames.get(i);
11324                    if (removeSharedLibraryLPw(name, 0)) {
11325                        if (DEBUG_REMOVE && chatty) {
11326                            if (r == null) {
11327                                r = new StringBuilder(256);
11328                            } else {
11329                                r.append(' ');
11330                            }
11331                            r.append(name);
11332                        }
11333                    }
11334                }
11335            }
11336        }
11337
11338        r = null;
11339
11340        // Any package can hold static shared libraries.
11341        if (pkg.staticSharedLibName != null) {
11342            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11343                if (DEBUG_REMOVE && chatty) {
11344                    if (r == null) {
11345                        r = new StringBuilder(256);
11346                    } else {
11347                        r.append(' ');
11348                    }
11349                    r.append(pkg.staticSharedLibName);
11350                }
11351            }
11352        }
11353
11354        if (r != null) {
11355            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11356        }
11357    }
11358
11359    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11360        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11361            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11362                return true;
11363            }
11364        }
11365        return false;
11366    }
11367
11368    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11369    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11370    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11371
11372    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11373        // Update the parent permissions
11374        updatePermissionsLPw(pkg.packageName, pkg, flags);
11375        // Update the child permissions
11376        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11377        for (int i = 0; i < childCount; i++) {
11378            PackageParser.Package childPkg = pkg.childPackages.get(i);
11379            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11380        }
11381    }
11382
11383    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11384            int flags) {
11385        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11386        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11387    }
11388
11389    private void updatePermissionsLPw(String changingPkg,
11390            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11391        // Make sure there are no dangling permission trees.
11392        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11393        while (it.hasNext()) {
11394            final BasePermission bp = it.next();
11395            if (bp.packageSetting == null) {
11396                // We may not yet have parsed the package, so just see if
11397                // we still know about its settings.
11398                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11399            }
11400            if (bp.packageSetting == null) {
11401                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11402                        + " from package " + bp.sourcePackage);
11403                it.remove();
11404            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11405                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11406                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11407                            + " from package " + bp.sourcePackage);
11408                    flags |= UPDATE_PERMISSIONS_ALL;
11409                    it.remove();
11410                }
11411            }
11412        }
11413
11414        // Make sure all dynamic permissions have been assigned to a package,
11415        // and make sure there are no dangling permissions.
11416        it = mSettings.mPermissions.values().iterator();
11417        while (it.hasNext()) {
11418            final BasePermission bp = it.next();
11419            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11420                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11421                        + bp.name + " pkg=" + bp.sourcePackage
11422                        + " info=" + bp.pendingInfo);
11423                if (bp.packageSetting == null && bp.pendingInfo != null) {
11424                    final BasePermission tree = findPermissionTreeLP(bp.name);
11425                    if (tree != null && tree.perm != null) {
11426                        bp.packageSetting = tree.packageSetting;
11427                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11428                                new PermissionInfo(bp.pendingInfo));
11429                        bp.perm.info.packageName = tree.perm.info.packageName;
11430                        bp.perm.info.name = bp.name;
11431                        bp.uid = tree.uid;
11432                    }
11433                }
11434            }
11435            if (bp.packageSetting == null) {
11436                // We may not yet have parsed the package, so just see if
11437                // we still know about its settings.
11438                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11439            }
11440            if (bp.packageSetting == null) {
11441                Slog.w(TAG, "Removing dangling permission: " + bp.name
11442                        + " from package " + bp.sourcePackage);
11443                it.remove();
11444            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11445                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11446                    Slog.i(TAG, "Removing old permission: " + bp.name
11447                            + " from package " + bp.sourcePackage);
11448                    flags |= UPDATE_PERMISSIONS_ALL;
11449                    it.remove();
11450                }
11451            }
11452        }
11453
11454        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11455        // Now update the permissions for all packages, in particular
11456        // replace the granted permissions of the system packages.
11457        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11458            for (PackageParser.Package pkg : mPackages.values()) {
11459                if (pkg != pkgInfo) {
11460                    // Only replace for packages on requested volume
11461                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11462                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11463                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11464                    grantPermissionsLPw(pkg, replace, changingPkg);
11465                }
11466            }
11467        }
11468
11469        if (pkgInfo != null) {
11470            // Only replace for packages on requested volume
11471            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11472            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11473                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11474            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11475        }
11476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11477    }
11478
11479    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11480            String packageOfInterest) {
11481        // IMPORTANT: There are two types of permissions: install and runtime.
11482        // Install time permissions are granted when the app is installed to
11483        // all device users and users added in the future. Runtime permissions
11484        // are granted at runtime explicitly to specific users. Normal and signature
11485        // protected permissions are install time permissions. Dangerous permissions
11486        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11487        // otherwise they are runtime permissions. This function does not manage
11488        // runtime permissions except for the case an app targeting Lollipop MR1
11489        // being upgraded to target a newer SDK, in which case dangerous permissions
11490        // are transformed from install time to runtime ones.
11491
11492        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11493        if (ps == null) {
11494            return;
11495        }
11496
11497        PermissionsState permissionsState = ps.getPermissionsState();
11498        PermissionsState origPermissions = permissionsState;
11499
11500        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11501
11502        boolean runtimePermissionsRevoked = false;
11503        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11504
11505        boolean changedInstallPermission = false;
11506
11507        if (replace) {
11508            ps.installPermissionsFixed = false;
11509            if (!ps.isSharedUser()) {
11510                origPermissions = new PermissionsState(permissionsState);
11511                permissionsState.reset();
11512            } else {
11513                // We need to know only about runtime permission changes since the
11514                // calling code always writes the install permissions state but
11515                // the runtime ones are written only if changed. The only cases of
11516                // changed runtime permissions here are promotion of an install to
11517                // runtime and revocation of a runtime from a shared user.
11518                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11519                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11520                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11521                    runtimePermissionsRevoked = true;
11522                }
11523            }
11524        }
11525
11526        permissionsState.setGlobalGids(mGlobalGids);
11527
11528        final int N = pkg.requestedPermissions.size();
11529        for (int i=0; i<N; i++) {
11530            final String name = pkg.requestedPermissions.get(i);
11531            final BasePermission bp = mSettings.mPermissions.get(name);
11532            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11533                    >= Build.VERSION_CODES.M;
11534
11535            if (DEBUG_INSTALL) {
11536                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11537            }
11538
11539            if (bp == null || bp.packageSetting == null) {
11540                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11541                    Slog.w(TAG, "Unknown permission " + name
11542                            + " in package " + pkg.packageName);
11543                }
11544                continue;
11545            }
11546
11547
11548            // Limit ephemeral apps to ephemeral allowed permissions.
11549            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11550                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11551                        + pkg.packageName);
11552                continue;
11553            }
11554
11555            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11556                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11557                        + pkg.packageName);
11558                continue;
11559            }
11560
11561            final String perm = bp.name;
11562            boolean allowedSig = false;
11563            int grant = GRANT_DENIED;
11564
11565            // Keep track of app op permissions.
11566            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11567                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11568                if (pkgs == null) {
11569                    pkgs = new ArraySet<>();
11570                    mAppOpPermissionPackages.put(bp.name, pkgs);
11571                }
11572                pkgs.add(pkg.packageName);
11573            }
11574
11575            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11576            switch (level) {
11577                case PermissionInfo.PROTECTION_NORMAL: {
11578                    // For all apps normal permissions are install time ones.
11579                    grant = GRANT_INSTALL;
11580                } break;
11581
11582                case PermissionInfo.PROTECTION_DANGEROUS: {
11583                    // If a permission review is required for legacy apps we represent
11584                    // their permissions as always granted runtime ones since we need
11585                    // to keep the review required permission flag per user while an
11586                    // install permission's state is shared across all users.
11587                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11588                        // For legacy apps dangerous permissions are install time ones.
11589                        grant = GRANT_INSTALL;
11590                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11591                        // For legacy apps that became modern, install becomes runtime.
11592                        grant = GRANT_UPGRADE;
11593                    } else if (mPromoteSystemApps
11594                            && isSystemApp(ps)
11595                            && mExistingSystemPackages.contains(ps.name)) {
11596                        // For legacy system apps, install becomes runtime.
11597                        // We cannot check hasInstallPermission() for system apps since those
11598                        // permissions were granted implicitly and not persisted pre-M.
11599                        grant = GRANT_UPGRADE;
11600                    } else {
11601                        // For modern apps keep runtime permissions unchanged.
11602                        grant = GRANT_RUNTIME;
11603                    }
11604                } break;
11605
11606                case PermissionInfo.PROTECTION_SIGNATURE: {
11607                    // For all apps signature permissions are install time ones.
11608                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11609                    if (allowedSig) {
11610                        grant = GRANT_INSTALL;
11611                    }
11612                } break;
11613            }
11614
11615            if (DEBUG_INSTALL) {
11616                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11617            }
11618
11619            if (grant != GRANT_DENIED) {
11620                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11621                    // If this is an existing, non-system package, then
11622                    // we can't add any new permissions to it.
11623                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11624                        // Except...  if this is a permission that was added
11625                        // to the platform (note: need to only do this when
11626                        // updating the platform).
11627                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11628                            grant = GRANT_DENIED;
11629                        }
11630                    }
11631                }
11632
11633                switch (grant) {
11634                    case GRANT_INSTALL: {
11635                        // Revoke this as runtime permission to handle the case of
11636                        // a runtime permission being downgraded to an install one.
11637                        // Also in permission review mode we keep dangerous permissions
11638                        // for legacy apps
11639                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11640                            if (origPermissions.getRuntimePermissionState(
11641                                    bp.name, userId) != null) {
11642                                // Revoke the runtime permission and clear the flags.
11643                                origPermissions.revokeRuntimePermission(bp, userId);
11644                                origPermissions.updatePermissionFlags(bp, userId,
11645                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11646                                // If we revoked a permission permission, we have to write.
11647                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11648                                        changedRuntimePermissionUserIds, userId);
11649                            }
11650                        }
11651                        // Grant an install permission.
11652                        if (permissionsState.grantInstallPermission(bp) !=
11653                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11654                            changedInstallPermission = true;
11655                        }
11656                    } break;
11657
11658                    case GRANT_RUNTIME: {
11659                        // Grant previously granted runtime permissions.
11660                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11661                            PermissionState permissionState = origPermissions
11662                                    .getRuntimePermissionState(bp.name, userId);
11663                            int flags = permissionState != null
11664                                    ? permissionState.getFlags() : 0;
11665                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11666                                // Don't propagate the permission in a permission review mode if
11667                                // the former was revoked, i.e. marked to not propagate on upgrade.
11668                                // Note that in a permission review mode install permissions are
11669                                // represented as constantly granted runtime ones since we need to
11670                                // keep a per user state associated with the permission. Also the
11671                                // revoke on upgrade flag is no longer applicable and is reset.
11672                                final boolean revokeOnUpgrade = (flags & PackageManager
11673                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11674                                if (revokeOnUpgrade) {
11675                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11676                                    // Since we changed the flags, we have to write.
11677                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11678                                            changedRuntimePermissionUserIds, userId);
11679                                }
11680                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11681                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11682                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11683                                        // If we cannot put the permission as it was,
11684                                        // we have to write.
11685                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11686                                                changedRuntimePermissionUserIds, userId);
11687                                    }
11688                                }
11689
11690                                // If the app supports runtime permissions no need for a review.
11691                                if (mPermissionReviewRequired
11692                                        && appSupportsRuntimePermissions
11693                                        && (flags & PackageManager
11694                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11695                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11696                                    // Since we changed the flags, we have to write.
11697                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11698                                            changedRuntimePermissionUserIds, userId);
11699                                }
11700                            } else if (mPermissionReviewRequired
11701                                    && !appSupportsRuntimePermissions) {
11702                                // For legacy apps that need a permission review, every new
11703                                // runtime permission is granted but it is pending a review.
11704                                // We also need to review only platform defined runtime
11705                                // permissions as these are the only ones the platform knows
11706                                // how to disable the API to simulate revocation as legacy
11707                                // apps don't expect to run with revoked permissions.
11708                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11709                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11710                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11711                                        // We changed the flags, hence have to write.
11712                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11713                                                changedRuntimePermissionUserIds, userId);
11714                                    }
11715                                }
11716                                if (permissionsState.grantRuntimePermission(bp, userId)
11717                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11718                                    // We changed the permission, hence have to write.
11719                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11720                                            changedRuntimePermissionUserIds, userId);
11721                                }
11722                            }
11723                            // Propagate the permission flags.
11724                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11725                        }
11726                    } break;
11727
11728                    case GRANT_UPGRADE: {
11729                        // Grant runtime permissions for a previously held install permission.
11730                        PermissionState permissionState = origPermissions
11731                                .getInstallPermissionState(bp.name);
11732                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11733
11734                        if (origPermissions.revokeInstallPermission(bp)
11735                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11736                            // We will be transferring the permission flags, so clear them.
11737                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11738                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11739                            changedInstallPermission = true;
11740                        }
11741
11742                        // If the permission is not to be promoted to runtime we ignore it and
11743                        // also its other flags as they are not applicable to install permissions.
11744                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11745                            for (int userId : currentUserIds) {
11746                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11747                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11748                                    // Transfer the permission flags.
11749                                    permissionsState.updatePermissionFlags(bp, userId,
11750                                            flags, flags);
11751                                    // If we granted the permission, we have to write.
11752                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11753                                            changedRuntimePermissionUserIds, userId);
11754                                }
11755                            }
11756                        }
11757                    } break;
11758
11759                    default: {
11760                        if (packageOfInterest == null
11761                                || packageOfInterest.equals(pkg.packageName)) {
11762                            Slog.w(TAG, "Not granting permission " + perm
11763                                    + " to package " + pkg.packageName
11764                                    + " because it was previously installed without");
11765                        }
11766                    } break;
11767                }
11768            } else {
11769                if (permissionsState.revokeInstallPermission(bp) !=
11770                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11771                    // Also drop the permission flags.
11772                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11773                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11774                    changedInstallPermission = true;
11775                    Slog.i(TAG, "Un-granting permission " + perm
11776                            + " from package " + pkg.packageName
11777                            + " (protectionLevel=" + bp.protectionLevel
11778                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11779                            + ")");
11780                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11781                    // Don't print warning for app op permissions, since it is fine for them
11782                    // not to be granted, there is a UI for the user to decide.
11783                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11784                        Slog.w(TAG, "Not granting permission " + perm
11785                                + " to package " + pkg.packageName
11786                                + " (protectionLevel=" + bp.protectionLevel
11787                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11788                                + ")");
11789                    }
11790                }
11791            }
11792        }
11793
11794        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11795                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11796            // This is the first that we have heard about this package, so the
11797            // permissions we have now selected are fixed until explicitly
11798            // changed.
11799            ps.installPermissionsFixed = true;
11800        }
11801
11802        // Persist the runtime permissions state for users with changes. If permissions
11803        // were revoked because no app in the shared user declares them we have to
11804        // write synchronously to avoid losing runtime permissions state.
11805        for (int userId : changedRuntimePermissionUserIds) {
11806            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11807        }
11808    }
11809
11810    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11811        boolean allowed = false;
11812        final int NP = PackageParser.NEW_PERMISSIONS.length;
11813        for (int ip=0; ip<NP; ip++) {
11814            final PackageParser.NewPermissionInfo npi
11815                    = PackageParser.NEW_PERMISSIONS[ip];
11816            if (npi.name.equals(perm)
11817                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11818                allowed = true;
11819                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11820                        + pkg.packageName);
11821                break;
11822            }
11823        }
11824        return allowed;
11825    }
11826
11827    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11828            BasePermission bp, PermissionsState origPermissions) {
11829        boolean privilegedPermission = (bp.protectionLevel
11830                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11831        boolean privappPermissionsDisable =
11832                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11833        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11834        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11835        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11836                && !platformPackage && platformPermission) {
11837            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11838                    .getPrivAppPermissions(pkg.packageName);
11839            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11840            if (!whitelisted) {
11841                Slog.w(TAG, "Privileged permission " + perm + " for package "
11842                        + pkg.packageName + " - not in privapp-permissions whitelist");
11843                // Only report violations for apps on system image
11844                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11845                    if (mPrivappPermissionsViolations == null) {
11846                        mPrivappPermissionsViolations = new ArraySet<>();
11847                    }
11848                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11849                }
11850                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11851                    return false;
11852                }
11853            }
11854        }
11855        boolean allowed = (compareSignatures(
11856                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11857                        == PackageManager.SIGNATURE_MATCH)
11858                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11859                        == PackageManager.SIGNATURE_MATCH);
11860        if (!allowed && privilegedPermission) {
11861            if (isSystemApp(pkg)) {
11862                // For updated system applications, a system permission
11863                // is granted only if it had been defined by the original application.
11864                if (pkg.isUpdatedSystemApp()) {
11865                    final PackageSetting sysPs = mSettings
11866                            .getDisabledSystemPkgLPr(pkg.packageName);
11867                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11868                        // If the original was granted this permission, we take
11869                        // that grant decision as read and propagate it to the
11870                        // update.
11871                        if (sysPs.isPrivileged()) {
11872                            allowed = true;
11873                        }
11874                    } else {
11875                        // The system apk may have been updated with an older
11876                        // version of the one on the data partition, but which
11877                        // granted a new system permission that it didn't have
11878                        // before.  In this case we do want to allow the app to
11879                        // now get the new permission if the ancestral apk is
11880                        // privileged to get it.
11881                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11882                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11883                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11884                                    allowed = true;
11885                                    break;
11886                                }
11887                            }
11888                        }
11889                        // Also if a privileged parent package on the system image or any of
11890                        // its children requested a privileged permission, the updated child
11891                        // packages can also get the permission.
11892                        if (pkg.parentPackage != null) {
11893                            final PackageSetting disabledSysParentPs = mSettings
11894                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11895                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11896                                    && disabledSysParentPs.isPrivileged()) {
11897                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11898                                    allowed = true;
11899                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11900                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11901                                    for (int i = 0; i < count; i++) {
11902                                        PackageParser.Package disabledSysChildPkg =
11903                                                disabledSysParentPs.pkg.childPackages.get(i);
11904                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11905                                                perm)) {
11906                                            allowed = true;
11907                                            break;
11908                                        }
11909                                    }
11910                                }
11911                            }
11912                        }
11913                    }
11914                } else {
11915                    allowed = isPrivilegedApp(pkg);
11916                }
11917            }
11918        }
11919        if (!allowed) {
11920            if (!allowed && (bp.protectionLevel
11921                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11922                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11923                // If this was a previously normal/dangerous permission that got moved
11924                // to a system permission as part of the runtime permission redesign, then
11925                // we still want to blindly grant it to old apps.
11926                allowed = true;
11927            }
11928            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11929                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11930                // If this permission is to be granted to the system installer and
11931                // this app is an installer, then it gets the permission.
11932                allowed = true;
11933            }
11934            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11935                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11936                // If this permission is to be granted to the system verifier and
11937                // this app is a verifier, then it gets the permission.
11938                allowed = true;
11939            }
11940            if (!allowed && (bp.protectionLevel
11941                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11942                    && isSystemApp(pkg)) {
11943                // Any pre-installed system app is allowed to get this permission.
11944                allowed = true;
11945            }
11946            if (!allowed && (bp.protectionLevel
11947                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11948                // For development permissions, a development permission
11949                // is granted only if it was already granted.
11950                allowed = origPermissions.hasInstallPermission(perm);
11951            }
11952            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11953                    && pkg.packageName.equals(mSetupWizardPackage)) {
11954                // If this permission is to be granted to the system setup wizard and
11955                // this app is a setup wizard, then it gets the permission.
11956                allowed = true;
11957            }
11958        }
11959        return allowed;
11960    }
11961
11962    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11963        final int permCount = pkg.requestedPermissions.size();
11964        for (int j = 0; j < permCount; j++) {
11965            String requestedPermission = pkg.requestedPermissions.get(j);
11966            if (permission.equals(requestedPermission)) {
11967                return true;
11968            }
11969        }
11970        return false;
11971    }
11972
11973    final class ActivityIntentResolver
11974            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11975        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11976                boolean defaultOnly, int userId) {
11977            if (!sUserManager.exists(userId)) return null;
11978            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11979            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11980        }
11981
11982        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11983                int userId) {
11984            if (!sUserManager.exists(userId)) return null;
11985            mFlags = flags;
11986            return super.queryIntent(intent, resolvedType,
11987                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11988                    userId);
11989        }
11990
11991        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11992                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11993            if (!sUserManager.exists(userId)) return null;
11994            if (packageActivities == null) {
11995                return null;
11996            }
11997            mFlags = flags;
11998            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11999            final int N = packageActivities.size();
12000            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12001                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12002
12003            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12004            for (int i = 0; i < N; ++i) {
12005                intentFilters = packageActivities.get(i).intents;
12006                if (intentFilters != null && intentFilters.size() > 0) {
12007                    PackageParser.ActivityIntentInfo[] array =
12008                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12009                    intentFilters.toArray(array);
12010                    listCut.add(array);
12011                }
12012            }
12013            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12014        }
12015
12016        /**
12017         * Finds a privileged activity that matches the specified activity names.
12018         */
12019        private PackageParser.Activity findMatchingActivity(
12020                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12021            for (PackageParser.Activity sysActivity : activityList) {
12022                if (sysActivity.info.name.equals(activityInfo.name)) {
12023                    return sysActivity;
12024                }
12025                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12026                    return sysActivity;
12027                }
12028                if (sysActivity.info.targetActivity != null) {
12029                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12030                        return sysActivity;
12031                    }
12032                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12033                        return sysActivity;
12034                    }
12035                }
12036            }
12037            return null;
12038        }
12039
12040        public class IterGenerator<E> {
12041            public Iterator<E> generate(ActivityIntentInfo info) {
12042                return null;
12043            }
12044        }
12045
12046        public class ActionIterGenerator extends IterGenerator<String> {
12047            @Override
12048            public Iterator<String> generate(ActivityIntentInfo info) {
12049                return info.actionsIterator();
12050            }
12051        }
12052
12053        public class CategoriesIterGenerator extends IterGenerator<String> {
12054            @Override
12055            public Iterator<String> generate(ActivityIntentInfo info) {
12056                return info.categoriesIterator();
12057            }
12058        }
12059
12060        public class SchemesIterGenerator extends IterGenerator<String> {
12061            @Override
12062            public Iterator<String> generate(ActivityIntentInfo info) {
12063                return info.schemesIterator();
12064            }
12065        }
12066
12067        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12068            @Override
12069            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12070                return info.authoritiesIterator();
12071            }
12072        }
12073
12074        /**
12075         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12076         * MODIFIED. Do not pass in a list that should not be changed.
12077         */
12078        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12079                IterGenerator<T> generator, Iterator<T> searchIterator) {
12080            // loop through the set of actions; every one must be found in the intent filter
12081            while (searchIterator.hasNext()) {
12082                // we must have at least one filter in the list to consider a match
12083                if (intentList.size() == 0) {
12084                    break;
12085                }
12086
12087                final T searchAction = searchIterator.next();
12088
12089                // loop through the set of intent filters
12090                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12091                while (intentIter.hasNext()) {
12092                    final ActivityIntentInfo intentInfo = intentIter.next();
12093                    boolean selectionFound = false;
12094
12095                    // loop through the intent filter's selection criteria; at least one
12096                    // of them must match the searched criteria
12097                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12098                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12099                        final T intentSelection = intentSelectionIter.next();
12100                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12101                            selectionFound = true;
12102                            break;
12103                        }
12104                    }
12105
12106                    // the selection criteria wasn't found in this filter's set; this filter
12107                    // is not a potential match
12108                    if (!selectionFound) {
12109                        intentIter.remove();
12110                    }
12111                }
12112            }
12113        }
12114
12115        private boolean isProtectedAction(ActivityIntentInfo filter) {
12116            final Iterator<String> actionsIter = filter.actionsIterator();
12117            while (actionsIter != null && actionsIter.hasNext()) {
12118                final String filterAction = actionsIter.next();
12119                if (PROTECTED_ACTIONS.contains(filterAction)) {
12120                    return true;
12121                }
12122            }
12123            return false;
12124        }
12125
12126        /**
12127         * Adjusts the priority of the given intent filter according to policy.
12128         * <p>
12129         * <ul>
12130         * <li>The priority for non privileged applications is capped to '0'</li>
12131         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12132         * <li>The priority for unbundled updates to privileged applications is capped to the
12133         *      priority defined on the system partition</li>
12134         * </ul>
12135         * <p>
12136         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12137         * allowed to obtain any priority on any action.
12138         */
12139        private void adjustPriority(
12140                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12141            // nothing to do; priority is fine as-is
12142            if (intent.getPriority() <= 0) {
12143                return;
12144            }
12145
12146            final ActivityInfo activityInfo = intent.activity.info;
12147            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12148
12149            final boolean privilegedApp =
12150                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12151            if (!privilegedApp) {
12152                // non-privileged applications can never define a priority >0
12153                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12154                        + " package: " + applicationInfo.packageName
12155                        + " activity: " + intent.activity.className
12156                        + " origPrio: " + intent.getPriority());
12157                intent.setPriority(0);
12158                return;
12159            }
12160
12161            if (systemActivities == null) {
12162                // the system package is not disabled; we're parsing the system partition
12163                if (isProtectedAction(intent)) {
12164                    if (mDeferProtectedFilters) {
12165                        // We can't deal with these just yet. No component should ever obtain a
12166                        // >0 priority for a protected actions, with ONE exception -- the setup
12167                        // wizard. The setup wizard, however, cannot be known until we're able to
12168                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12169                        // until all intent filters have been processed. Chicken, meet egg.
12170                        // Let the filter temporarily have a high priority and rectify the
12171                        // priorities after all system packages have been scanned.
12172                        mProtectedFilters.add(intent);
12173                        if (DEBUG_FILTERS) {
12174                            Slog.i(TAG, "Protected action; save for later;"
12175                                    + " package: " + applicationInfo.packageName
12176                                    + " activity: " + intent.activity.className
12177                                    + " origPrio: " + intent.getPriority());
12178                        }
12179                        return;
12180                    } else {
12181                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12182                            Slog.i(TAG, "No setup wizard;"
12183                                + " All protected intents capped to priority 0");
12184                        }
12185                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12186                            if (DEBUG_FILTERS) {
12187                                Slog.i(TAG, "Found setup wizard;"
12188                                    + " allow priority " + intent.getPriority() + ";"
12189                                    + " package: " + intent.activity.info.packageName
12190                                    + " activity: " + intent.activity.className
12191                                    + " priority: " + intent.getPriority());
12192                            }
12193                            // setup wizard gets whatever it wants
12194                            return;
12195                        }
12196                        Slog.w(TAG, "Protected action; cap priority to 0;"
12197                                + " package: " + intent.activity.info.packageName
12198                                + " activity: " + intent.activity.className
12199                                + " origPrio: " + intent.getPriority());
12200                        intent.setPriority(0);
12201                        return;
12202                    }
12203                }
12204                // privileged apps on the system image get whatever priority they request
12205                return;
12206            }
12207
12208            // privileged app unbundled update ... try to find the same activity
12209            final PackageParser.Activity foundActivity =
12210                    findMatchingActivity(systemActivities, activityInfo);
12211            if (foundActivity == null) {
12212                // this is a new activity; it cannot obtain >0 priority
12213                if (DEBUG_FILTERS) {
12214                    Slog.i(TAG, "New activity; cap priority to 0;"
12215                            + " package: " + applicationInfo.packageName
12216                            + " activity: " + intent.activity.className
12217                            + " origPrio: " + intent.getPriority());
12218                }
12219                intent.setPriority(0);
12220                return;
12221            }
12222
12223            // found activity, now check for filter equivalence
12224
12225            // a shallow copy is enough; we modify the list, not its contents
12226            final List<ActivityIntentInfo> intentListCopy =
12227                    new ArrayList<>(foundActivity.intents);
12228            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12229
12230            // find matching action subsets
12231            final Iterator<String> actionsIterator = intent.actionsIterator();
12232            if (actionsIterator != null) {
12233                getIntentListSubset(
12234                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12235                if (intentListCopy.size() == 0) {
12236                    // no more intents to match; we're not equivalent
12237                    if (DEBUG_FILTERS) {
12238                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12239                                + " package: " + applicationInfo.packageName
12240                                + " activity: " + intent.activity.className
12241                                + " origPrio: " + intent.getPriority());
12242                    }
12243                    intent.setPriority(0);
12244                    return;
12245                }
12246            }
12247
12248            // find matching category subsets
12249            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12250            if (categoriesIterator != null) {
12251                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12252                        categoriesIterator);
12253                if (intentListCopy.size() == 0) {
12254                    // no more intents to match; we're not equivalent
12255                    if (DEBUG_FILTERS) {
12256                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12257                                + " package: " + applicationInfo.packageName
12258                                + " activity: " + intent.activity.className
12259                                + " origPrio: " + intent.getPriority());
12260                    }
12261                    intent.setPriority(0);
12262                    return;
12263                }
12264            }
12265
12266            // find matching schemes subsets
12267            final Iterator<String> schemesIterator = intent.schemesIterator();
12268            if (schemesIterator != null) {
12269                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12270                        schemesIterator);
12271                if (intentListCopy.size() == 0) {
12272                    // no more intents to match; we're not equivalent
12273                    if (DEBUG_FILTERS) {
12274                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12275                                + " package: " + applicationInfo.packageName
12276                                + " activity: " + intent.activity.className
12277                                + " origPrio: " + intent.getPriority());
12278                    }
12279                    intent.setPriority(0);
12280                    return;
12281                }
12282            }
12283
12284            // find matching authorities subsets
12285            final Iterator<IntentFilter.AuthorityEntry>
12286                    authoritiesIterator = intent.authoritiesIterator();
12287            if (authoritiesIterator != null) {
12288                getIntentListSubset(intentListCopy,
12289                        new AuthoritiesIterGenerator(),
12290                        authoritiesIterator);
12291                if (intentListCopy.size() == 0) {
12292                    // no more intents to match; we're not equivalent
12293                    if (DEBUG_FILTERS) {
12294                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12295                                + " package: " + applicationInfo.packageName
12296                                + " activity: " + intent.activity.className
12297                                + " origPrio: " + intent.getPriority());
12298                    }
12299                    intent.setPriority(0);
12300                    return;
12301                }
12302            }
12303
12304            // we found matching filter(s); app gets the max priority of all intents
12305            int cappedPriority = 0;
12306            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12307                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12308            }
12309            if (intent.getPriority() > cappedPriority) {
12310                if (DEBUG_FILTERS) {
12311                    Slog.i(TAG, "Found matching filter(s);"
12312                            + " cap priority to " + cappedPriority + ";"
12313                            + " package: " + applicationInfo.packageName
12314                            + " activity: " + intent.activity.className
12315                            + " origPrio: " + intent.getPriority());
12316                }
12317                intent.setPriority(cappedPriority);
12318                return;
12319            }
12320            // all this for nothing; the requested priority was <= what was on the system
12321        }
12322
12323        public final void addActivity(PackageParser.Activity a, String type) {
12324            mActivities.put(a.getComponentName(), a);
12325            if (DEBUG_SHOW_INFO)
12326                Log.v(
12327                TAG, "  " + type + " " +
12328                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12329            if (DEBUG_SHOW_INFO)
12330                Log.v(TAG, "    Class=" + a.info.name);
12331            final int NI = a.intents.size();
12332            for (int j=0; j<NI; j++) {
12333                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12334                if ("activity".equals(type)) {
12335                    final PackageSetting ps =
12336                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12337                    final List<PackageParser.Activity> systemActivities =
12338                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12339                    adjustPriority(systemActivities, intent);
12340                }
12341                if (DEBUG_SHOW_INFO) {
12342                    Log.v(TAG, "    IntentFilter:");
12343                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12344                }
12345                if (!intent.debugCheck()) {
12346                    Log.w(TAG, "==> For Activity " + a.info.name);
12347                }
12348                addFilter(intent);
12349            }
12350        }
12351
12352        public final void removeActivity(PackageParser.Activity a, String type) {
12353            mActivities.remove(a.getComponentName());
12354            if (DEBUG_SHOW_INFO) {
12355                Log.v(TAG, "  " + type + " "
12356                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12357                                : a.info.name) + ":");
12358                Log.v(TAG, "    Class=" + a.info.name);
12359            }
12360            final int NI = a.intents.size();
12361            for (int j=0; j<NI; j++) {
12362                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12363                if (DEBUG_SHOW_INFO) {
12364                    Log.v(TAG, "    IntentFilter:");
12365                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12366                }
12367                removeFilter(intent);
12368            }
12369        }
12370
12371        @Override
12372        protected boolean allowFilterResult(
12373                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12374            ActivityInfo filterAi = filter.activity.info;
12375            for (int i=dest.size()-1; i>=0; i--) {
12376                ActivityInfo destAi = dest.get(i).activityInfo;
12377                if (destAi.name == filterAi.name
12378                        && destAi.packageName == filterAi.packageName) {
12379                    return false;
12380                }
12381            }
12382            return true;
12383        }
12384
12385        @Override
12386        protected ActivityIntentInfo[] newArray(int size) {
12387            return new ActivityIntentInfo[size];
12388        }
12389
12390        @Override
12391        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12392            if (!sUserManager.exists(userId)) return true;
12393            PackageParser.Package p = filter.activity.owner;
12394            if (p != null) {
12395                PackageSetting ps = (PackageSetting)p.mExtras;
12396                if (ps != null) {
12397                    // System apps are never considered stopped for purposes of
12398                    // filtering, because there may be no way for the user to
12399                    // actually re-launch them.
12400                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12401                            && ps.getStopped(userId);
12402                }
12403            }
12404            return false;
12405        }
12406
12407        @Override
12408        protected boolean isPackageForFilter(String packageName,
12409                PackageParser.ActivityIntentInfo info) {
12410            return packageName.equals(info.activity.owner.packageName);
12411        }
12412
12413        @Override
12414        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12415                int match, int userId) {
12416            if (!sUserManager.exists(userId)) return null;
12417            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12418                return null;
12419            }
12420            final PackageParser.Activity activity = info.activity;
12421            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12422            if (ps == null) {
12423                return null;
12424            }
12425            final PackageUserState userState = ps.readUserState(userId);
12426            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12427            if (ai == null) {
12428                return null;
12429            }
12430            final boolean matchVisibleToInstantApp =
12431                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12432            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12433            // throw out filters that aren't visible to ephemeral apps
12434            if (matchVisibleToInstantApp
12435                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12436                return null;
12437            }
12438            // throw out ephemeral filters if we're not explicitly requesting them
12439            if (!isInstantApp && userState.instantApp) {
12440                return null;
12441            }
12442            // throw out instant app filters if updates are available; will trigger
12443            // instant app resolution
12444            if (userState.instantApp && ps.isUpdateAvailable()) {
12445                return null;
12446            }
12447            final ResolveInfo res = new ResolveInfo();
12448            res.activityInfo = ai;
12449            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12450                res.filter = info;
12451            }
12452            if (info != null) {
12453                res.handleAllWebDataURI = info.handleAllWebDataURI();
12454            }
12455            res.priority = info.getPriority();
12456            res.preferredOrder = activity.owner.mPreferredOrder;
12457            //System.out.println("Result: " + res.activityInfo.className +
12458            //                   " = " + res.priority);
12459            res.match = match;
12460            res.isDefault = info.hasDefault;
12461            res.labelRes = info.labelRes;
12462            res.nonLocalizedLabel = info.nonLocalizedLabel;
12463            if (userNeedsBadging(userId)) {
12464                res.noResourceId = true;
12465            } else {
12466                res.icon = info.icon;
12467            }
12468            res.iconResourceId = info.icon;
12469            res.system = res.activityInfo.applicationInfo.isSystemApp();
12470            res.instantAppAvailable = userState.instantApp;
12471            return res;
12472        }
12473
12474        @Override
12475        protected void sortResults(List<ResolveInfo> results) {
12476            Collections.sort(results, mResolvePrioritySorter);
12477        }
12478
12479        @Override
12480        protected void dumpFilter(PrintWriter out, String prefix,
12481                PackageParser.ActivityIntentInfo filter) {
12482            out.print(prefix); out.print(
12483                    Integer.toHexString(System.identityHashCode(filter.activity)));
12484                    out.print(' ');
12485                    filter.activity.printComponentShortName(out);
12486                    out.print(" filter ");
12487                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12488        }
12489
12490        @Override
12491        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12492            return filter.activity;
12493        }
12494
12495        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12496            PackageParser.Activity activity = (PackageParser.Activity)label;
12497            out.print(prefix); out.print(
12498                    Integer.toHexString(System.identityHashCode(activity)));
12499                    out.print(' ');
12500                    activity.printComponentShortName(out);
12501            if (count > 1) {
12502                out.print(" ("); out.print(count); out.print(" filters)");
12503            }
12504            out.println();
12505        }
12506
12507        // Keys are String (activity class name), values are Activity.
12508        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12509                = new ArrayMap<ComponentName, PackageParser.Activity>();
12510        private int mFlags;
12511    }
12512
12513    private final class ServiceIntentResolver
12514            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12515        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12516                boolean defaultOnly, int userId) {
12517            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12518            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12519        }
12520
12521        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12522                int userId) {
12523            if (!sUserManager.exists(userId)) return null;
12524            mFlags = flags;
12525            return super.queryIntent(intent, resolvedType,
12526                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12527                    userId);
12528        }
12529
12530        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12531                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12532            if (!sUserManager.exists(userId)) return null;
12533            if (packageServices == null) {
12534                return null;
12535            }
12536            mFlags = flags;
12537            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12538            final int N = packageServices.size();
12539            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12540                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12541
12542            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12543            for (int i = 0; i < N; ++i) {
12544                intentFilters = packageServices.get(i).intents;
12545                if (intentFilters != null && intentFilters.size() > 0) {
12546                    PackageParser.ServiceIntentInfo[] array =
12547                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12548                    intentFilters.toArray(array);
12549                    listCut.add(array);
12550                }
12551            }
12552            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12553        }
12554
12555        public final void addService(PackageParser.Service s) {
12556            mServices.put(s.getComponentName(), s);
12557            if (DEBUG_SHOW_INFO) {
12558                Log.v(TAG, "  "
12559                        + (s.info.nonLocalizedLabel != null
12560                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12561                Log.v(TAG, "    Class=" + s.info.name);
12562            }
12563            final int NI = s.intents.size();
12564            int j;
12565            for (j=0; j<NI; j++) {
12566                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12567                if (DEBUG_SHOW_INFO) {
12568                    Log.v(TAG, "    IntentFilter:");
12569                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12570                }
12571                if (!intent.debugCheck()) {
12572                    Log.w(TAG, "==> For Service " + s.info.name);
12573                }
12574                addFilter(intent);
12575            }
12576        }
12577
12578        public final void removeService(PackageParser.Service s) {
12579            mServices.remove(s.getComponentName());
12580            if (DEBUG_SHOW_INFO) {
12581                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12582                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12583                Log.v(TAG, "    Class=" + s.info.name);
12584            }
12585            final int NI = s.intents.size();
12586            int j;
12587            for (j=0; j<NI; j++) {
12588                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12589                if (DEBUG_SHOW_INFO) {
12590                    Log.v(TAG, "    IntentFilter:");
12591                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12592                }
12593                removeFilter(intent);
12594            }
12595        }
12596
12597        @Override
12598        protected boolean allowFilterResult(
12599                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12600            ServiceInfo filterSi = filter.service.info;
12601            for (int i=dest.size()-1; i>=0; i--) {
12602                ServiceInfo destAi = dest.get(i).serviceInfo;
12603                if (destAi.name == filterSi.name
12604                        && destAi.packageName == filterSi.packageName) {
12605                    return false;
12606                }
12607            }
12608            return true;
12609        }
12610
12611        @Override
12612        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12613            return new PackageParser.ServiceIntentInfo[size];
12614        }
12615
12616        @Override
12617        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12618            if (!sUserManager.exists(userId)) return true;
12619            PackageParser.Package p = filter.service.owner;
12620            if (p != null) {
12621                PackageSetting ps = (PackageSetting)p.mExtras;
12622                if (ps != null) {
12623                    // System apps are never considered stopped for purposes of
12624                    // filtering, because there may be no way for the user to
12625                    // actually re-launch them.
12626                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12627                            && ps.getStopped(userId);
12628                }
12629            }
12630            return false;
12631        }
12632
12633        @Override
12634        protected boolean isPackageForFilter(String packageName,
12635                PackageParser.ServiceIntentInfo info) {
12636            return packageName.equals(info.service.owner.packageName);
12637        }
12638
12639        @Override
12640        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12641                int match, int userId) {
12642            if (!sUserManager.exists(userId)) return null;
12643            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12644            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12645                return null;
12646            }
12647            final PackageParser.Service service = info.service;
12648            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12649            if (ps == null) {
12650                return null;
12651            }
12652            final PackageUserState userState = ps.readUserState(userId);
12653            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12654                    userState, userId);
12655            if (si == null) {
12656                return null;
12657            }
12658            final boolean matchVisibleToInstantApp =
12659                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12660            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12661            // throw out filters that aren't visible to ephemeral apps
12662            if (matchVisibleToInstantApp
12663                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12664                return null;
12665            }
12666            // throw out ephemeral filters if we're not explicitly requesting them
12667            if (!isInstantApp && userState.instantApp) {
12668                return null;
12669            }
12670            // throw out instant app filters if updates are available; will trigger
12671            // instant app resolution
12672            if (userState.instantApp && ps.isUpdateAvailable()) {
12673                return null;
12674            }
12675            final ResolveInfo res = new ResolveInfo();
12676            res.serviceInfo = si;
12677            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12678                res.filter = filter;
12679            }
12680            res.priority = info.getPriority();
12681            res.preferredOrder = service.owner.mPreferredOrder;
12682            res.match = match;
12683            res.isDefault = info.hasDefault;
12684            res.labelRes = info.labelRes;
12685            res.nonLocalizedLabel = info.nonLocalizedLabel;
12686            res.icon = info.icon;
12687            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12688            return res;
12689        }
12690
12691        @Override
12692        protected void sortResults(List<ResolveInfo> results) {
12693            Collections.sort(results, mResolvePrioritySorter);
12694        }
12695
12696        @Override
12697        protected void dumpFilter(PrintWriter out, String prefix,
12698                PackageParser.ServiceIntentInfo filter) {
12699            out.print(prefix); out.print(
12700                    Integer.toHexString(System.identityHashCode(filter.service)));
12701                    out.print(' ');
12702                    filter.service.printComponentShortName(out);
12703                    out.print(" filter ");
12704                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12705        }
12706
12707        @Override
12708        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12709            return filter.service;
12710        }
12711
12712        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12713            PackageParser.Service service = (PackageParser.Service)label;
12714            out.print(prefix); out.print(
12715                    Integer.toHexString(System.identityHashCode(service)));
12716                    out.print(' ');
12717                    service.printComponentShortName(out);
12718            if (count > 1) {
12719                out.print(" ("); out.print(count); out.print(" filters)");
12720            }
12721            out.println();
12722        }
12723
12724//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12725//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12726//            final List<ResolveInfo> retList = Lists.newArrayList();
12727//            while (i.hasNext()) {
12728//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12729//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12730//                    retList.add(resolveInfo);
12731//                }
12732//            }
12733//            return retList;
12734//        }
12735
12736        // Keys are String (activity class name), values are Activity.
12737        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12738                = new ArrayMap<ComponentName, PackageParser.Service>();
12739        private int mFlags;
12740    }
12741
12742    private final class ProviderIntentResolver
12743            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12744        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12745                boolean defaultOnly, int userId) {
12746            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12747            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12748        }
12749
12750        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12751                int userId) {
12752            if (!sUserManager.exists(userId))
12753                return null;
12754            mFlags = flags;
12755            return super.queryIntent(intent, resolvedType,
12756                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12757                    userId);
12758        }
12759
12760        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12761                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12762            if (!sUserManager.exists(userId))
12763                return null;
12764            if (packageProviders == null) {
12765                return null;
12766            }
12767            mFlags = flags;
12768            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12769            final int N = packageProviders.size();
12770            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12771                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12772
12773            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12774            for (int i = 0; i < N; ++i) {
12775                intentFilters = packageProviders.get(i).intents;
12776                if (intentFilters != null && intentFilters.size() > 0) {
12777                    PackageParser.ProviderIntentInfo[] array =
12778                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12779                    intentFilters.toArray(array);
12780                    listCut.add(array);
12781                }
12782            }
12783            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12784        }
12785
12786        public final void addProvider(PackageParser.Provider p) {
12787            if (mProviders.containsKey(p.getComponentName())) {
12788                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12789                return;
12790            }
12791
12792            mProviders.put(p.getComponentName(), p);
12793            if (DEBUG_SHOW_INFO) {
12794                Log.v(TAG, "  "
12795                        + (p.info.nonLocalizedLabel != null
12796                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12797                Log.v(TAG, "    Class=" + p.info.name);
12798            }
12799            final int NI = p.intents.size();
12800            int j;
12801            for (j = 0; j < NI; j++) {
12802                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12803                if (DEBUG_SHOW_INFO) {
12804                    Log.v(TAG, "    IntentFilter:");
12805                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12806                }
12807                if (!intent.debugCheck()) {
12808                    Log.w(TAG, "==> For Provider " + p.info.name);
12809                }
12810                addFilter(intent);
12811            }
12812        }
12813
12814        public final void removeProvider(PackageParser.Provider p) {
12815            mProviders.remove(p.getComponentName());
12816            if (DEBUG_SHOW_INFO) {
12817                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12818                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12819                Log.v(TAG, "    Class=" + p.info.name);
12820            }
12821            final int NI = p.intents.size();
12822            int j;
12823            for (j = 0; j < NI; j++) {
12824                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12825                if (DEBUG_SHOW_INFO) {
12826                    Log.v(TAG, "    IntentFilter:");
12827                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12828                }
12829                removeFilter(intent);
12830            }
12831        }
12832
12833        @Override
12834        protected boolean allowFilterResult(
12835                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12836            ProviderInfo filterPi = filter.provider.info;
12837            for (int i = dest.size() - 1; i >= 0; i--) {
12838                ProviderInfo destPi = dest.get(i).providerInfo;
12839                if (destPi.name == filterPi.name
12840                        && destPi.packageName == filterPi.packageName) {
12841                    return false;
12842                }
12843            }
12844            return true;
12845        }
12846
12847        @Override
12848        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12849            return new PackageParser.ProviderIntentInfo[size];
12850        }
12851
12852        @Override
12853        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12854            if (!sUserManager.exists(userId))
12855                return true;
12856            PackageParser.Package p = filter.provider.owner;
12857            if (p != null) {
12858                PackageSetting ps = (PackageSetting) p.mExtras;
12859                if (ps != null) {
12860                    // System apps are never considered stopped for purposes of
12861                    // filtering, because there may be no way for the user to
12862                    // actually re-launch them.
12863                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12864                            && ps.getStopped(userId);
12865                }
12866            }
12867            return false;
12868        }
12869
12870        @Override
12871        protected boolean isPackageForFilter(String packageName,
12872                PackageParser.ProviderIntentInfo info) {
12873            return packageName.equals(info.provider.owner.packageName);
12874        }
12875
12876        @Override
12877        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12878                int match, int userId) {
12879            if (!sUserManager.exists(userId))
12880                return null;
12881            final PackageParser.ProviderIntentInfo info = filter;
12882            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12883                return null;
12884            }
12885            final PackageParser.Provider provider = info.provider;
12886            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12887            if (ps == null) {
12888                return null;
12889            }
12890            final PackageUserState userState = ps.readUserState(userId);
12891            final boolean matchVisibleToInstantApp =
12892                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12893            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12894            // throw out filters that aren't visible to instant applications
12895            if (matchVisibleToInstantApp
12896                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12897                return null;
12898            }
12899            // throw out instant application filters if we're not explicitly requesting them
12900            if (!isInstantApp && userState.instantApp) {
12901                return null;
12902            }
12903            // throw out instant application filters if updates are available; will trigger
12904            // instant application resolution
12905            if (userState.instantApp && ps.isUpdateAvailable()) {
12906                return null;
12907            }
12908            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12909                    userState, userId);
12910            if (pi == null) {
12911                return null;
12912            }
12913            final ResolveInfo res = new ResolveInfo();
12914            res.providerInfo = pi;
12915            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12916                res.filter = filter;
12917            }
12918            res.priority = info.getPriority();
12919            res.preferredOrder = provider.owner.mPreferredOrder;
12920            res.match = match;
12921            res.isDefault = info.hasDefault;
12922            res.labelRes = info.labelRes;
12923            res.nonLocalizedLabel = info.nonLocalizedLabel;
12924            res.icon = info.icon;
12925            res.system = res.providerInfo.applicationInfo.isSystemApp();
12926            return res;
12927        }
12928
12929        @Override
12930        protected void sortResults(List<ResolveInfo> results) {
12931            Collections.sort(results, mResolvePrioritySorter);
12932        }
12933
12934        @Override
12935        protected void dumpFilter(PrintWriter out, String prefix,
12936                PackageParser.ProviderIntentInfo filter) {
12937            out.print(prefix);
12938            out.print(
12939                    Integer.toHexString(System.identityHashCode(filter.provider)));
12940            out.print(' ');
12941            filter.provider.printComponentShortName(out);
12942            out.print(" filter ");
12943            out.println(Integer.toHexString(System.identityHashCode(filter)));
12944        }
12945
12946        @Override
12947        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12948            return filter.provider;
12949        }
12950
12951        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12952            PackageParser.Provider provider = (PackageParser.Provider)label;
12953            out.print(prefix); out.print(
12954                    Integer.toHexString(System.identityHashCode(provider)));
12955                    out.print(' ');
12956                    provider.printComponentShortName(out);
12957            if (count > 1) {
12958                out.print(" ("); out.print(count); out.print(" filters)");
12959            }
12960            out.println();
12961        }
12962
12963        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12964                = new ArrayMap<ComponentName, PackageParser.Provider>();
12965        private int mFlags;
12966    }
12967
12968    static final class EphemeralIntentResolver
12969            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12970        /**
12971         * The result that has the highest defined order. Ordering applies on a
12972         * per-package basis. Mapping is from package name to Pair of order and
12973         * EphemeralResolveInfo.
12974         * <p>
12975         * NOTE: This is implemented as a field variable for convenience and efficiency.
12976         * By having a field variable, we're able to track filter ordering as soon as
12977         * a non-zero order is defined. Otherwise, multiple loops across the result set
12978         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12979         * this needs to be contained entirely within {@link #filterResults}.
12980         */
12981        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12982
12983        @Override
12984        protected AuxiliaryResolveInfo[] newArray(int size) {
12985            return new AuxiliaryResolveInfo[size];
12986        }
12987
12988        @Override
12989        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12990            return true;
12991        }
12992
12993        @Override
12994        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12995                int userId) {
12996            if (!sUserManager.exists(userId)) {
12997                return null;
12998            }
12999            final String packageName = responseObj.resolveInfo.getPackageName();
13000            final Integer order = responseObj.getOrder();
13001            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13002                    mOrderResult.get(packageName);
13003            // ordering is enabled and this item's order isn't high enough
13004            if (lastOrderResult != null && lastOrderResult.first >= order) {
13005                return null;
13006            }
13007            final InstantAppResolveInfo res = responseObj.resolveInfo;
13008            if (order > 0) {
13009                // non-zero order, enable ordering
13010                mOrderResult.put(packageName, new Pair<>(order, res));
13011            }
13012            return responseObj;
13013        }
13014
13015        @Override
13016        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13017            // only do work if ordering is enabled [most of the time it won't be]
13018            if (mOrderResult.size() == 0) {
13019                return;
13020            }
13021            int resultSize = results.size();
13022            for (int i = 0; i < resultSize; i++) {
13023                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13024                final String packageName = info.getPackageName();
13025                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13026                if (savedInfo == null) {
13027                    // package doesn't having ordering
13028                    continue;
13029                }
13030                if (savedInfo.second == info) {
13031                    // circled back to the highest ordered item; remove from order list
13032                    mOrderResult.remove(savedInfo);
13033                    if (mOrderResult.size() == 0) {
13034                        // no more ordered items
13035                        break;
13036                    }
13037                    continue;
13038                }
13039                // item has a worse order, remove it from the result list
13040                results.remove(i);
13041                resultSize--;
13042                i--;
13043            }
13044        }
13045    }
13046
13047    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13048            new Comparator<ResolveInfo>() {
13049        public int compare(ResolveInfo r1, ResolveInfo r2) {
13050            int v1 = r1.priority;
13051            int v2 = r2.priority;
13052            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13053            if (v1 != v2) {
13054                return (v1 > v2) ? -1 : 1;
13055            }
13056            v1 = r1.preferredOrder;
13057            v2 = r2.preferredOrder;
13058            if (v1 != v2) {
13059                return (v1 > v2) ? -1 : 1;
13060            }
13061            if (r1.isDefault != r2.isDefault) {
13062                return r1.isDefault ? -1 : 1;
13063            }
13064            v1 = r1.match;
13065            v2 = r2.match;
13066            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13067            if (v1 != v2) {
13068                return (v1 > v2) ? -1 : 1;
13069            }
13070            if (r1.system != r2.system) {
13071                return r1.system ? -1 : 1;
13072            }
13073            if (r1.activityInfo != null) {
13074                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13075            }
13076            if (r1.serviceInfo != null) {
13077                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13078            }
13079            if (r1.providerInfo != null) {
13080                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13081            }
13082            return 0;
13083        }
13084    };
13085
13086    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13087            new Comparator<ProviderInfo>() {
13088        public int compare(ProviderInfo p1, ProviderInfo p2) {
13089            final int v1 = p1.initOrder;
13090            final int v2 = p2.initOrder;
13091            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13092        }
13093    };
13094
13095    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13096            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13097            final int[] userIds) {
13098        mHandler.post(new Runnable() {
13099            @Override
13100            public void run() {
13101                try {
13102                    final IActivityManager am = ActivityManager.getService();
13103                    if (am == null) return;
13104                    final int[] resolvedUserIds;
13105                    if (userIds == null) {
13106                        resolvedUserIds = am.getRunningUserIds();
13107                    } else {
13108                        resolvedUserIds = userIds;
13109                    }
13110                    for (int id : resolvedUserIds) {
13111                        final Intent intent = new Intent(action,
13112                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13113                        if (extras != null) {
13114                            intent.putExtras(extras);
13115                        }
13116                        if (targetPkg != null) {
13117                            intent.setPackage(targetPkg);
13118                        }
13119                        // Modify the UID when posting to other users
13120                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13121                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13122                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13123                            intent.putExtra(Intent.EXTRA_UID, uid);
13124                        }
13125                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13126                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13127                        if (DEBUG_BROADCASTS) {
13128                            RuntimeException here = new RuntimeException("here");
13129                            here.fillInStackTrace();
13130                            Slog.d(TAG, "Sending to user " + id + ": "
13131                                    + intent.toShortString(false, true, false, false)
13132                                    + " " + intent.getExtras(), here);
13133                        }
13134                        am.broadcastIntent(null, intent, null, finishedReceiver,
13135                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13136                                null, finishedReceiver != null, false, id);
13137                    }
13138                } catch (RemoteException ex) {
13139                }
13140            }
13141        });
13142    }
13143
13144    /**
13145     * Check if the external storage media is available. This is true if there
13146     * is a mounted external storage medium or if the external storage is
13147     * emulated.
13148     */
13149    private boolean isExternalMediaAvailable() {
13150        return mMediaMounted || Environment.isExternalStorageEmulated();
13151    }
13152
13153    @Override
13154    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13155        // writer
13156        synchronized (mPackages) {
13157            if (!isExternalMediaAvailable()) {
13158                // If the external storage is no longer mounted at this point,
13159                // the caller may not have been able to delete all of this
13160                // packages files and can not delete any more.  Bail.
13161                return null;
13162            }
13163            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13164            if (lastPackage != null) {
13165                pkgs.remove(lastPackage);
13166            }
13167            if (pkgs.size() > 0) {
13168                return pkgs.get(0);
13169            }
13170        }
13171        return null;
13172    }
13173
13174    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13175        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13176                userId, andCode ? 1 : 0, packageName);
13177        if (mSystemReady) {
13178            msg.sendToTarget();
13179        } else {
13180            if (mPostSystemReadyMessages == null) {
13181                mPostSystemReadyMessages = new ArrayList<>();
13182            }
13183            mPostSystemReadyMessages.add(msg);
13184        }
13185    }
13186
13187    void startCleaningPackages() {
13188        // reader
13189        if (!isExternalMediaAvailable()) {
13190            return;
13191        }
13192        synchronized (mPackages) {
13193            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13194                return;
13195            }
13196        }
13197        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13198        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13199        IActivityManager am = ActivityManager.getService();
13200        if (am != null) {
13201            int dcsUid = -1;
13202            synchronized (mPackages) {
13203                if (!mDefaultContainerWhitelisted) {
13204                    mDefaultContainerWhitelisted = true;
13205                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13206                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13207                }
13208            }
13209            try {
13210                if (dcsUid > 0) {
13211                    am.backgroundWhitelistUid(dcsUid);
13212                }
13213                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13214                        UserHandle.USER_SYSTEM);
13215            } catch (RemoteException e) {
13216            }
13217        }
13218    }
13219
13220    @Override
13221    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13222            int installFlags, String installerPackageName, int userId) {
13223        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13224
13225        final int callingUid = Binder.getCallingUid();
13226        enforceCrossUserPermission(callingUid, userId,
13227                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13228
13229        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13230            try {
13231                if (observer != null) {
13232                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13233                }
13234            } catch (RemoteException re) {
13235            }
13236            return;
13237        }
13238
13239        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13240            installFlags |= PackageManager.INSTALL_FROM_ADB;
13241
13242        } else {
13243            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13244            // about installerPackageName.
13245
13246            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13247            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13248        }
13249
13250        UserHandle user;
13251        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13252            user = UserHandle.ALL;
13253        } else {
13254            user = new UserHandle(userId);
13255        }
13256
13257        // Only system components can circumvent runtime permissions when installing.
13258        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13259                && mContext.checkCallingOrSelfPermission(Manifest.permission
13260                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13261            throw new SecurityException("You need the "
13262                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13263                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13264        }
13265
13266        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13267                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13268            throw new IllegalArgumentException(
13269                    "New installs into ASEC containers no longer supported");
13270        }
13271
13272        final File originFile = new File(originPath);
13273        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13274
13275        final Message msg = mHandler.obtainMessage(INIT_COPY);
13276        final VerificationInfo verificationInfo = new VerificationInfo(
13277                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13278        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13279                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13280                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13281                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13282        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13283        msg.obj = params;
13284
13285        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13286                System.identityHashCode(msg.obj));
13287        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13288                System.identityHashCode(msg.obj));
13289
13290        mHandler.sendMessage(msg);
13291    }
13292
13293
13294    /**
13295     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13296     * it is acting on behalf on an enterprise or the user).
13297     *
13298     * Note that the ordering of the conditionals in this method is important. The checks we perform
13299     * are as follows, in this order:
13300     *
13301     * 1) If the install is being performed by a system app, we can trust the app to have set the
13302     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13303     *    what it is.
13304     * 2) If the install is being performed by a device or profile owner app, the install reason
13305     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13306     *    set the install reason correctly. If the app targets an older SDK version where install
13307     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13308     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13309     * 3) In all other cases, the install is being performed by a regular app that is neither part
13310     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13311     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13312     *    set to enterprise policy and if so, change it to unknown instead.
13313     */
13314    private int fixUpInstallReason(String installerPackageName, int installerUid,
13315            int installReason) {
13316        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13317                == PERMISSION_GRANTED) {
13318            // If the install is being performed by a system app, we trust that app to have set the
13319            // install reason correctly.
13320            return installReason;
13321        }
13322
13323        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13324            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13325        if (dpm != null) {
13326            ComponentName owner = null;
13327            try {
13328                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13329                if (owner == null) {
13330                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13331                }
13332            } catch (RemoteException e) {
13333            }
13334            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13335                // If the install is being performed by a device or profile owner, the install
13336                // reason should be enterprise policy.
13337                return PackageManager.INSTALL_REASON_POLICY;
13338            }
13339        }
13340
13341        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13342            // If the install is being performed by a regular app (i.e. neither system app nor
13343            // device or profile owner), we have no reason to believe that the app is acting on
13344            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13345            // change it to unknown instead.
13346            return PackageManager.INSTALL_REASON_UNKNOWN;
13347        }
13348
13349        // If the install is being performed by a regular app and the install reason was set to any
13350        // value but enterprise policy, leave the install reason unchanged.
13351        return installReason;
13352    }
13353
13354    void installStage(String packageName, File stagedDir, String stagedCid,
13355            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13356            String installerPackageName, int installerUid, UserHandle user,
13357            Certificate[][] certificates) {
13358        if (DEBUG_EPHEMERAL) {
13359            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13360                Slog.d(TAG, "Ephemeral install of " + packageName);
13361            }
13362        }
13363        final VerificationInfo verificationInfo = new VerificationInfo(
13364                sessionParams.originatingUri, sessionParams.referrerUri,
13365                sessionParams.originatingUid, installerUid);
13366
13367        final OriginInfo origin;
13368        if (stagedDir != null) {
13369            origin = OriginInfo.fromStagedFile(stagedDir);
13370        } else {
13371            origin = OriginInfo.fromStagedContainer(stagedCid);
13372        }
13373
13374        final Message msg = mHandler.obtainMessage(INIT_COPY);
13375        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13376                sessionParams.installReason);
13377        final InstallParams params = new InstallParams(origin, null, observer,
13378                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13379                verificationInfo, user, sessionParams.abiOverride,
13380                sessionParams.grantedRuntimePermissions, certificates, installReason);
13381        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13382        msg.obj = params;
13383
13384        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13385                System.identityHashCode(msg.obj));
13386        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13387                System.identityHashCode(msg.obj));
13388
13389        mHandler.sendMessage(msg);
13390    }
13391
13392    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13393            int userId) {
13394        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13395        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13396    }
13397
13398    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13399        if (ArrayUtils.isEmpty(userIds)) {
13400            return;
13401        }
13402        Bundle extras = new Bundle(1);
13403        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13404        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13405
13406        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13407                packageName, extras, 0, null, null, userIds);
13408        if (isSystem) {
13409            mHandler.post(() -> {
13410                        for (int userId : userIds) {
13411                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13412                        }
13413                    }
13414            );
13415        }
13416    }
13417
13418    /**
13419     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13420     * automatically without needing an explicit launch.
13421     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13422     */
13423    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13424        // If user is not running, the app didn't miss any broadcast
13425        if (!mUserManagerInternal.isUserRunning(userId)) {
13426            return;
13427        }
13428        final IActivityManager am = ActivityManager.getService();
13429        try {
13430            // Deliver LOCKED_BOOT_COMPLETED first
13431            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13432                    .setPackage(packageName);
13433            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13434            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13435                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13436
13437            // Deliver BOOT_COMPLETED only if user is unlocked
13438            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13439                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13440                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13441                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13442            }
13443        } catch (RemoteException e) {
13444            throw e.rethrowFromSystemServer();
13445        }
13446    }
13447
13448    @Override
13449    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13450            int userId) {
13451        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13452        PackageSetting pkgSetting;
13453        final int uid = Binder.getCallingUid();
13454        enforceCrossUserPermission(uid, userId,
13455                true /* requireFullPermission */, true /* checkShell */,
13456                "setApplicationHiddenSetting for user " + userId);
13457
13458        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13459            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13460            return false;
13461        }
13462
13463        long callingId = Binder.clearCallingIdentity();
13464        try {
13465            boolean sendAdded = false;
13466            boolean sendRemoved = false;
13467            // writer
13468            synchronized (mPackages) {
13469                pkgSetting = mSettings.mPackages.get(packageName);
13470                if (pkgSetting == null) {
13471                    return false;
13472                }
13473                // Do not allow "android" is being disabled
13474                if ("android".equals(packageName)) {
13475                    Slog.w(TAG, "Cannot hide package: android");
13476                    return false;
13477                }
13478                // Cannot hide static shared libs as they are considered
13479                // a part of the using app (emulating static linking). Also
13480                // static libs are installed always on internal storage.
13481                PackageParser.Package pkg = mPackages.get(packageName);
13482                if (pkg != null && pkg.staticSharedLibName != null) {
13483                    Slog.w(TAG, "Cannot hide package: " + packageName
13484                            + " providing static shared library: "
13485                            + pkg.staticSharedLibName);
13486                    return false;
13487                }
13488                // Only allow protected packages to hide themselves.
13489                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13490                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13491                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13492                    return false;
13493                }
13494
13495                if (pkgSetting.getHidden(userId) != hidden) {
13496                    pkgSetting.setHidden(hidden, userId);
13497                    mSettings.writePackageRestrictionsLPr(userId);
13498                    if (hidden) {
13499                        sendRemoved = true;
13500                    } else {
13501                        sendAdded = true;
13502                    }
13503                }
13504            }
13505            if (sendAdded) {
13506                sendPackageAddedForUser(packageName, pkgSetting, userId);
13507                return true;
13508            }
13509            if (sendRemoved) {
13510                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13511                        "hiding pkg");
13512                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13513                return true;
13514            }
13515        } finally {
13516            Binder.restoreCallingIdentity(callingId);
13517        }
13518        return false;
13519    }
13520
13521    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13522            int userId) {
13523        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13524        info.removedPackage = packageName;
13525        info.removedUsers = new int[] {userId};
13526        info.broadcastUsers = new int[] {userId};
13527        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13528        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13529    }
13530
13531    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13532        if (pkgList.length > 0) {
13533            Bundle extras = new Bundle(1);
13534            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13535
13536            sendPackageBroadcast(
13537                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13538                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13539                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13540                    new int[] {userId});
13541        }
13542    }
13543
13544    /**
13545     * Returns true if application is not found or there was an error. Otherwise it returns
13546     * the hidden state of the package for the given user.
13547     */
13548    @Override
13549    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13550        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13551        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13552                true /* requireFullPermission */, false /* checkShell */,
13553                "getApplicationHidden for user " + userId);
13554        PackageSetting pkgSetting;
13555        long callingId = Binder.clearCallingIdentity();
13556        try {
13557            // writer
13558            synchronized (mPackages) {
13559                pkgSetting = mSettings.mPackages.get(packageName);
13560                if (pkgSetting == null) {
13561                    return true;
13562                }
13563                return pkgSetting.getHidden(userId);
13564            }
13565        } finally {
13566            Binder.restoreCallingIdentity(callingId);
13567        }
13568    }
13569
13570    /**
13571     * @hide
13572     */
13573    @Override
13574    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13575            int installReason) {
13576        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13577                null);
13578        PackageSetting pkgSetting;
13579        final int uid = Binder.getCallingUid();
13580        enforceCrossUserPermission(uid, userId,
13581                true /* requireFullPermission */, true /* checkShell */,
13582                "installExistingPackage for user " + userId);
13583        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13584            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13585        }
13586
13587        long callingId = Binder.clearCallingIdentity();
13588        try {
13589            boolean installed = false;
13590            final boolean instantApp =
13591                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13592            final boolean fullApp =
13593                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13594
13595            // writer
13596            synchronized (mPackages) {
13597                pkgSetting = mSettings.mPackages.get(packageName);
13598                if (pkgSetting == null) {
13599                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13600                }
13601                if (!pkgSetting.getInstalled(userId)) {
13602                    pkgSetting.setInstalled(true, userId);
13603                    pkgSetting.setHidden(false, userId);
13604                    pkgSetting.setInstallReason(installReason, userId);
13605                    mSettings.writePackageRestrictionsLPr(userId);
13606                    mSettings.writeKernelMappingLPr(pkgSetting);
13607                    installed = true;
13608                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13609                    // upgrade app from instant to full; we don't allow app downgrade
13610                    installed = true;
13611                }
13612                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13613            }
13614
13615            if (installed) {
13616                if (pkgSetting.pkg != null) {
13617                    synchronized (mInstallLock) {
13618                        // We don't need to freeze for a brand new install
13619                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13620                    }
13621                }
13622                sendPackageAddedForUser(packageName, pkgSetting, userId);
13623                synchronized (mPackages) {
13624                    updateSequenceNumberLP(packageName, new int[]{ userId });
13625                }
13626            }
13627        } finally {
13628            Binder.restoreCallingIdentity(callingId);
13629        }
13630
13631        return PackageManager.INSTALL_SUCCEEDED;
13632    }
13633
13634    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13635            boolean instantApp, boolean fullApp) {
13636        // no state specified; do nothing
13637        if (!instantApp && !fullApp) {
13638            return;
13639        }
13640        if (userId != UserHandle.USER_ALL) {
13641            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13642                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13643            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13644                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13645            }
13646        } else {
13647            for (int currentUserId : sUserManager.getUserIds()) {
13648                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13649                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13650                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13651                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13652                }
13653            }
13654        }
13655    }
13656
13657    boolean isUserRestricted(int userId, String restrictionKey) {
13658        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13659        if (restrictions.getBoolean(restrictionKey, false)) {
13660            Log.w(TAG, "User is restricted: " + restrictionKey);
13661            return true;
13662        }
13663        return false;
13664    }
13665
13666    @Override
13667    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13668            int userId) {
13669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13670        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13671                true /* requireFullPermission */, true /* checkShell */,
13672                "setPackagesSuspended for user " + userId);
13673
13674        if (ArrayUtils.isEmpty(packageNames)) {
13675            return packageNames;
13676        }
13677
13678        // List of package names for whom the suspended state has changed.
13679        List<String> changedPackages = new ArrayList<>(packageNames.length);
13680        // List of package names for whom the suspended state is not set as requested in this
13681        // method.
13682        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13683        long callingId = Binder.clearCallingIdentity();
13684        try {
13685            for (int i = 0; i < packageNames.length; i++) {
13686                String packageName = packageNames[i];
13687                boolean changed = false;
13688                final int appId;
13689                synchronized (mPackages) {
13690                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13691                    if (pkgSetting == null) {
13692                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13693                                + "\". Skipping suspending/un-suspending.");
13694                        unactionedPackages.add(packageName);
13695                        continue;
13696                    }
13697                    appId = pkgSetting.appId;
13698                    if (pkgSetting.getSuspended(userId) != suspended) {
13699                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13700                            unactionedPackages.add(packageName);
13701                            continue;
13702                        }
13703                        pkgSetting.setSuspended(suspended, userId);
13704                        mSettings.writePackageRestrictionsLPr(userId);
13705                        changed = true;
13706                        changedPackages.add(packageName);
13707                    }
13708                }
13709
13710                if (changed && suspended) {
13711                    killApplication(packageName, UserHandle.getUid(userId, appId),
13712                            "suspending package");
13713                }
13714            }
13715        } finally {
13716            Binder.restoreCallingIdentity(callingId);
13717        }
13718
13719        if (!changedPackages.isEmpty()) {
13720            sendPackagesSuspendedForUser(changedPackages.toArray(
13721                    new String[changedPackages.size()]), userId, suspended);
13722        }
13723
13724        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13725    }
13726
13727    @Override
13728    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13729        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13730                true /* requireFullPermission */, false /* checkShell */,
13731                "isPackageSuspendedForUser for user " + userId);
13732        synchronized (mPackages) {
13733            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13734            if (pkgSetting == null) {
13735                throw new IllegalArgumentException("Unknown target package: " + packageName);
13736            }
13737            return pkgSetting.getSuspended(userId);
13738        }
13739    }
13740
13741    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13742        if (isPackageDeviceAdmin(packageName, userId)) {
13743            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13744                    + "\": has an active device admin");
13745            return false;
13746        }
13747
13748        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13749        if (packageName.equals(activeLauncherPackageName)) {
13750            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13751                    + "\": contains the active launcher");
13752            return false;
13753        }
13754
13755        if (packageName.equals(mRequiredInstallerPackage)) {
13756            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13757                    + "\": required for package installation");
13758            return false;
13759        }
13760
13761        if (packageName.equals(mRequiredUninstallerPackage)) {
13762            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13763                    + "\": required for package uninstallation");
13764            return false;
13765        }
13766
13767        if (packageName.equals(mRequiredVerifierPackage)) {
13768            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13769                    + "\": required for package verification");
13770            return false;
13771        }
13772
13773        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13774            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13775                    + "\": is the default dialer");
13776            return false;
13777        }
13778
13779        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13780            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13781                    + "\": protected package");
13782            return false;
13783        }
13784
13785        // Cannot suspend static shared libs as they are considered
13786        // a part of the using app (emulating static linking). Also
13787        // static libs are installed always on internal storage.
13788        PackageParser.Package pkg = mPackages.get(packageName);
13789        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13790            Slog.w(TAG, "Cannot suspend package: " + packageName
13791                    + " providing static shared library: "
13792                    + pkg.staticSharedLibName);
13793            return false;
13794        }
13795
13796        return true;
13797    }
13798
13799    private String getActiveLauncherPackageName(int userId) {
13800        Intent intent = new Intent(Intent.ACTION_MAIN);
13801        intent.addCategory(Intent.CATEGORY_HOME);
13802        ResolveInfo resolveInfo = resolveIntent(
13803                intent,
13804                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13805                PackageManager.MATCH_DEFAULT_ONLY,
13806                userId);
13807
13808        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13809    }
13810
13811    private String getDefaultDialerPackageName(int userId) {
13812        synchronized (mPackages) {
13813            return mSettings.getDefaultDialerPackageNameLPw(userId);
13814        }
13815    }
13816
13817    @Override
13818    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13819        mContext.enforceCallingOrSelfPermission(
13820                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13821                "Only package verification agents can verify applications");
13822
13823        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13824        final PackageVerificationResponse response = new PackageVerificationResponse(
13825                verificationCode, Binder.getCallingUid());
13826        msg.arg1 = id;
13827        msg.obj = response;
13828        mHandler.sendMessage(msg);
13829    }
13830
13831    @Override
13832    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13833            long millisecondsToDelay) {
13834        mContext.enforceCallingOrSelfPermission(
13835                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13836                "Only package verification agents can extend verification timeouts");
13837
13838        final PackageVerificationState state = mPendingVerification.get(id);
13839        final PackageVerificationResponse response = new PackageVerificationResponse(
13840                verificationCodeAtTimeout, Binder.getCallingUid());
13841
13842        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13843            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13844        }
13845        if (millisecondsToDelay < 0) {
13846            millisecondsToDelay = 0;
13847        }
13848        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13849                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13850            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13851        }
13852
13853        if ((state != null) && !state.timeoutExtended()) {
13854            state.extendTimeout();
13855
13856            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13857            msg.arg1 = id;
13858            msg.obj = response;
13859            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13860        }
13861    }
13862
13863    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13864            int verificationCode, UserHandle user) {
13865        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13866        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13867        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13868        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13869        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13870
13871        mContext.sendBroadcastAsUser(intent, user,
13872                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13873    }
13874
13875    private ComponentName matchComponentForVerifier(String packageName,
13876            List<ResolveInfo> receivers) {
13877        ActivityInfo targetReceiver = null;
13878
13879        final int NR = receivers.size();
13880        for (int i = 0; i < NR; i++) {
13881            final ResolveInfo info = receivers.get(i);
13882            if (info.activityInfo == null) {
13883                continue;
13884            }
13885
13886            if (packageName.equals(info.activityInfo.packageName)) {
13887                targetReceiver = info.activityInfo;
13888                break;
13889            }
13890        }
13891
13892        if (targetReceiver == null) {
13893            return null;
13894        }
13895
13896        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13897    }
13898
13899    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13900            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13901        if (pkgInfo.verifiers.length == 0) {
13902            return null;
13903        }
13904
13905        final int N = pkgInfo.verifiers.length;
13906        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13907        for (int i = 0; i < N; i++) {
13908            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13909
13910            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13911                    receivers);
13912            if (comp == null) {
13913                continue;
13914            }
13915
13916            final int verifierUid = getUidForVerifier(verifierInfo);
13917            if (verifierUid == -1) {
13918                continue;
13919            }
13920
13921            if (DEBUG_VERIFY) {
13922                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13923                        + " with the correct signature");
13924            }
13925            sufficientVerifiers.add(comp);
13926            verificationState.addSufficientVerifier(verifierUid);
13927        }
13928
13929        return sufficientVerifiers;
13930    }
13931
13932    private int getUidForVerifier(VerifierInfo verifierInfo) {
13933        synchronized (mPackages) {
13934            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13935            if (pkg == null) {
13936                return -1;
13937            } else if (pkg.mSignatures.length != 1) {
13938                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13939                        + " has more than one signature; ignoring");
13940                return -1;
13941            }
13942
13943            /*
13944             * If the public key of the package's signature does not match
13945             * our expected public key, then this is a different package and
13946             * we should skip.
13947             */
13948
13949            final byte[] expectedPublicKey;
13950            try {
13951                final Signature verifierSig = pkg.mSignatures[0];
13952                final PublicKey publicKey = verifierSig.getPublicKey();
13953                expectedPublicKey = publicKey.getEncoded();
13954            } catch (CertificateException e) {
13955                return -1;
13956            }
13957
13958            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13959
13960            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13961                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13962                        + " does not have the expected public key; ignoring");
13963                return -1;
13964            }
13965
13966            return pkg.applicationInfo.uid;
13967        }
13968    }
13969
13970    @Override
13971    public void finishPackageInstall(int token, boolean didLaunch) {
13972        enforceSystemOrRoot("Only the system is allowed to finish installs");
13973
13974        if (DEBUG_INSTALL) {
13975            Slog.v(TAG, "BM finishing package install for " + token);
13976        }
13977        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13978
13979        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13980        mHandler.sendMessage(msg);
13981    }
13982
13983    /**
13984     * Get the verification agent timeout.  Used for both the APK verifier and the
13985     * intent filter verifier.
13986     *
13987     * @return verification timeout in milliseconds
13988     */
13989    private long getVerificationTimeout() {
13990        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13991                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13992                DEFAULT_VERIFICATION_TIMEOUT);
13993    }
13994
13995    /**
13996     * Get the default verification agent response code.
13997     *
13998     * @return default verification response code
13999     */
14000    private int getDefaultVerificationResponse() {
14001        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14002                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14003                DEFAULT_VERIFICATION_RESPONSE);
14004    }
14005
14006    /**
14007     * Check whether or not package verification has been enabled.
14008     *
14009     * @return true if verification should be performed
14010     */
14011    private boolean isVerificationEnabled(int userId, int installFlags) {
14012        if (!DEFAULT_VERIFY_ENABLE) {
14013            return false;
14014        }
14015
14016        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14017
14018        // Check if installing from ADB
14019        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14020            // Do not run verification in a test harness environment
14021            if (ActivityManager.isRunningInTestHarness()) {
14022                return false;
14023            }
14024            if (ensureVerifyAppsEnabled) {
14025                return true;
14026            }
14027            // Check if the developer does not want package verification for ADB installs
14028            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14029                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14030                return false;
14031            }
14032        }
14033
14034        if (ensureVerifyAppsEnabled) {
14035            return true;
14036        }
14037
14038        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14039                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14040    }
14041
14042    @Override
14043    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14044            throws RemoteException {
14045        mContext.enforceCallingOrSelfPermission(
14046                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14047                "Only intentfilter verification agents can verify applications");
14048
14049        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14050        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14051                Binder.getCallingUid(), verificationCode, failedDomains);
14052        msg.arg1 = id;
14053        msg.obj = response;
14054        mHandler.sendMessage(msg);
14055    }
14056
14057    @Override
14058    public int getIntentVerificationStatus(String packageName, int userId) {
14059        synchronized (mPackages) {
14060            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14061        }
14062    }
14063
14064    @Override
14065    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14066        mContext.enforceCallingOrSelfPermission(
14067                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14068
14069        boolean result = false;
14070        synchronized (mPackages) {
14071            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14072        }
14073        if (result) {
14074            scheduleWritePackageRestrictionsLocked(userId);
14075        }
14076        return result;
14077    }
14078
14079    @Override
14080    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14081            String packageName) {
14082        synchronized (mPackages) {
14083            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14084        }
14085    }
14086
14087    @Override
14088    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14089        if (TextUtils.isEmpty(packageName)) {
14090            return ParceledListSlice.emptyList();
14091        }
14092        synchronized (mPackages) {
14093            PackageParser.Package pkg = mPackages.get(packageName);
14094            if (pkg == null || pkg.activities == null) {
14095                return ParceledListSlice.emptyList();
14096            }
14097            final int count = pkg.activities.size();
14098            ArrayList<IntentFilter> result = new ArrayList<>();
14099            for (int n=0; n<count; n++) {
14100                PackageParser.Activity activity = pkg.activities.get(n);
14101                if (activity.intents != null && activity.intents.size() > 0) {
14102                    result.addAll(activity.intents);
14103                }
14104            }
14105            return new ParceledListSlice<>(result);
14106        }
14107    }
14108
14109    @Override
14110    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14111        mContext.enforceCallingOrSelfPermission(
14112                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14113
14114        synchronized (mPackages) {
14115            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14116            if (packageName != null) {
14117                result |= updateIntentVerificationStatus(packageName,
14118                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
14119                        userId);
14120                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14121                        packageName, userId);
14122            }
14123            return result;
14124        }
14125    }
14126
14127    @Override
14128    public String getDefaultBrowserPackageName(int userId) {
14129        synchronized (mPackages) {
14130            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14131        }
14132    }
14133
14134    /**
14135     * Get the "allow unknown sources" setting.
14136     *
14137     * @return the current "allow unknown sources" setting
14138     */
14139    private int getUnknownSourcesSettings() {
14140        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14141                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14142                -1);
14143    }
14144
14145    @Override
14146    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14147        final int uid = Binder.getCallingUid();
14148        // writer
14149        synchronized (mPackages) {
14150            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14151            if (targetPackageSetting == null) {
14152                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14153            }
14154
14155            PackageSetting installerPackageSetting;
14156            if (installerPackageName != null) {
14157                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14158                if (installerPackageSetting == null) {
14159                    throw new IllegalArgumentException("Unknown installer package: "
14160                            + installerPackageName);
14161                }
14162            } else {
14163                installerPackageSetting = null;
14164            }
14165
14166            Signature[] callerSignature;
14167            Object obj = mSettings.getUserIdLPr(uid);
14168            if (obj != null) {
14169                if (obj instanceof SharedUserSetting) {
14170                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14171                } else if (obj instanceof PackageSetting) {
14172                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14173                } else {
14174                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14175                }
14176            } else {
14177                throw new SecurityException("Unknown calling UID: " + uid);
14178            }
14179
14180            // Verify: can't set installerPackageName to a package that is
14181            // not signed with the same cert as the caller.
14182            if (installerPackageSetting != null) {
14183                if (compareSignatures(callerSignature,
14184                        installerPackageSetting.signatures.mSignatures)
14185                        != PackageManager.SIGNATURE_MATCH) {
14186                    throw new SecurityException(
14187                            "Caller does not have same cert as new installer package "
14188                            + installerPackageName);
14189                }
14190            }
14191
14192            // Verify: if target already has an installer package, it must
14193            // be signed with the same cert as the caller.
14194            if (targetPackageSetting.installerPackageName != null) {
14195                PackageSetting setting = mSettings.mPackages.get(
14196                        targetPackageSetting.installerPackageName);
14197                // If the currently set package isn't valid, then it's always
14198                // okay to change it.
14199                if (setting != null) {
14200                    if (compareSignatures(callerSignature,
14201                            setting.signatures.mSignatures)
14202                            != PackageManager.SIGNATURE_MATCH) {
14203                        throw new SecurityException(
14204                                "Caller does not have same cert as old installer package "
14205                                + targetPackageSetting.installerPackageName);
14206                    }
14207                }
14208            }
14209
14210            // Okay!
14211            targetPackageSetting.installerPackageName = installerPackageName;
14212            if (installerPackageName != null) {
14213                mSettings.mInstallerPackages.add(installerPackageName);
14214            }
14215            scheduleWriteSettingsLocked();
14216        }
14217    }
14218
14219    @Override
14220    public void setApplicationCategoryHint(String packageName, int categoryHint,
14221            String callerPackageName) {
14222        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14223                callerPackageName);
14224        synchronized (mPackages) {
14225            PackageSetting ps = mSettings.mPackages.get(packageName);
14226            if (ps == null) {
14227                throw new IllegalArgumentException("Unknown target package " + packageName);
14228            }
14229
14230            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14231                throw new IllegalArgumentException("Calling package " + callerPackageName
14232                        + " is not installer for " + packageName);
14233            }
14234
14235            if (ps.categoryHint != categoryHint) {
14236                ps.categoryHint = categoryHint;
14237                scheduleWriteSettingsLocked();
14238            }
14239        }
14240    }
14241
14242    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14243        // Queue up an async operation since the package installation may take a little while.
14244        mHandler.post(new Runnable() {
14245            public void run() {
14246                mHandler.removeCallbacks(this);
14247                 // Result object to be returned
14248                PackageInstalledInfo res = new PackageInstalledInfo();
14249                res.setReturnCode(currentStatus);
14250                res.uid = -1;
14251                res.pkg = null;
14252                res.removedInfo = null;
14253                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14254                    args.doPreInstall(res.returnCode);
14255                    synchronized (mInstallLock) {
14256                        installPackageTracedLI(args, res);
14257                    }
14258                    args.doPostInstall(res.returnCode, res.uid);
14259                }
14260
14261                // A restore should be performed at this point if (a) the install
14262                // succeeded, (b) the operation is not an update, and (c) the new
14263                // package has not opted out of backup participation.
14264                final boolean update = res.removedInfo != null
14265                        && res.removedInfo.removedPackage != null;
14266                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14267                boolean doRestore = !update
14268                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14269
14270                // Set up the post-install work request bookkeeping.  This will be used
14271                // and cleaned up by the post-install event handling regardless of whether
14272                // there's a restore pass performed.  Token values are >= 1.
14273                int token;
14274                if (mNextInstallToken < 0) mNextInstallToken = 1;
14275                token = mNextInstallToken++;
14276
14277                PostInstallData data = new PostInstallData(args, res);
14278                mRunningInstalls.put(token, data);
14279                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14280
14281                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14282                    // Pass responsibility to the Backup Manager.  It will perform a
14283                    // restore if appropriate, then pass responsibility back to the
14284                    // Package Manager to run the post-install observer callbacks
14285                    // and broadcasts.
14286                    IBackupManager bm = IBackupManager.Stub.asInterface(
14287                            ServiceManager.getService(Context.BACKUP_SERVICE));
14288                    if (bm != null) {
14289                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14290                                + " to BM for possible restore");
14291                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14292                        try {
14293                            // TODO: http://b/22388012
14294                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14295                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14296                            } else {
14297                                doRestore = false;
14298                            }
14299                        } catch (RemoteException e) {
14300                            // can't happen; the backup manager is local
14301                        } catch (Exception e) {
14302                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14303                            doRestore = false;
14304                        }
14305                    } else {
14306                        Slog.e(TAG, "Backup Manager not found!");
14307                        doRestore = false;
14308                    }
14309                }
14310
14311                if (!doRestore) {
14312                    // No restore possible, or the Backup Manager was mysteriously not
14313                    // available -- just fire the post-install work request directly.
14314                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14315
14316                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14317
14318                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14319                    mHandler.sendMessage(msg);
14320                }
14321            }
14322        });
14323    }
14324
14325    /**
14326     * Callback from PackageSettings whenever an app is first transitioned out of the
14327     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14328     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14329     * here whether the app is the target of an ongoing install, and only send the
14330     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14331     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14332     * handling.
14333     */
14334    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14335        // Serialize this with the rest of the install-process message chain.  In the
14336        // restore-at-install case, this Runnable will necessarily run before the
14337        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14338        // are coherent.  In the non-restore case, the app has already completed install
14339        // and been launched through some other means, so it is not in a problematic
14340        // state for observers to see the FIRST_LAUNCH signal.
14341        mHandler.post(new Runnable() {
14342            @Override
14343            public void run() {
14344                for (int i = 0; i < mRunningInstalls.size(); i++) {
14345                    final PostInstallData data = mRunningInstalls.valueAt(i);
14346                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14347                        continue;
14348                    }
14349                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14350                        // right package; but is it for the right user?
14351                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14352                            if (userId == data.res.newUsers[uIndex]) {
14353                                if (DEBUG_BACKUP) {
14354                                    Slog.i(TAG, "Package " + pkgName
14355                                            + " being restored so deferring FIRST_LAUNCH");
14356                                }
14357                                return;
14358                            }
14359                        }
14360                    }
14361                }
14362                // didn't find it, so not being restored
14363                if (DEBUG_BACKUP) {
14364                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14365                }
14366                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14367            }
14368        });
14369    }
14370
14371    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14372        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14373                installerPkg, null, userIds);
14374    }
14375
14376    private abstract class HandlerParams {
14377        private static final int MAX_RETRIES = 4;
14378
14379        /**
14380         * Number of times startCopy() has been attempted and had a non-fatal
14381         * error.
14382         */
14383        private int mRetries = 0;
14384
14385        /** User handle for the user requesting the information or installation. */
14386        private final UserHandle mUser;
14387        String traceMethod;
14388        int traceCookie;
14389
14390        HandlerParams(UserHandle user) {
14391            mUser = user;
14392        }
14393
14394        UserHandle getUser() {
14395            return mUser;
14396        }
14397
14398        HandlerParams setTraceMethod(String traceMethod) {
14399            this.traceMethod = traceMethod;
14400            return this;
14401        }
14402
14403        HandlerParams setTraceCookie(int traceCookie) {
14404            this.traceCookie = traceCookie;
14405            return this;
14406        }
14407
14408        final boolean startCopy() {
14409            boolean res;
14410            try {
14411                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14412
14413                if (++mRetries > MAX_RETRIES) {
14414                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14415                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14416                    handleServiceError();
14417                    return false;
14418                } else {
14419                    handleStartCopy();
14420                    res = true;
14421                }
14422            } catch (RemoteException e) {
14423                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14424                mHandler.sendEmptyMessage(MCS_RECONNECT);
14425                res = false;
14426            }
14427            handleReturnCode();
14428            return res;
14429        }
14430
14431        final void serviceError() {
14432            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14433            handleServiceError();
14434            handleReturnCode();
14435        }
14436
14437        abstract void handleStartCopy() throws RemoteException;
14438        abstract void handleServiceError();
14439        abstract void handleReturnCode();
14440    }
14441
14442    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14443        for (File path : paths) {
14444            try {
14445                mcs.clearDirectory(path.getAbsolutePath());
14446            } catch (RemoteException e) {
14447            }
14448        }
14449    }
14450
14451    static class OriginInfo {
14452        /**
14453         * Location where install is coming from, before it has been
14454         * copied/renamed into place. This could be a single monolithic APK
14455         * file, or a cluster directory. This location may be untrusted.
14456         */
14457        final File file;
14458        final String cid;
14459
14460        /**
14461         * Flag indicating that {@link #file} or {@link #cid} has already been
14462         * staged, meaning downstream users don't need to defensively copy the
14463         * contents.
14464         */
14465        final boolean staged;
14466
14467        /**
14468         * Flag indicating that {@link #file} or {@link #cid} is an already
14469         * installed app that is being moved.
14470         */
14471        final boolean existing;
14472
14473        final String resolvedPath;
14474        final File resolvedFile;
14475
14476        static OriginInfo fromNothing() {
14477            return new OriginInfo(null, null, false, false);
14478        }
14479
14480        static OriginInfo fromUntrustedFile(File file) {
14481            return new OriginInfo(file, null, false, false);
14482        }
14483
14484        static OriginInfo fromExistingFile(File file) {
14485            return new OriginInfo(file, null, false, true);
14486        }
14487
14488        static OriginInfo fromStagedFile(File file) {
14489            return new OriginInfo(file, null, true, false);
14490        }
14491
14492        static OriginInfo fromStagedContainer(String cid) {
14493            return new OriginInfo(null, cid, true, false);
14494        }
14495
14496        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14497            this.file = file;
14498            this.cid = cid;
14499            this.staged = staged;
14500            this.existing = existing;
14501
14502            if (cid != null) {
14503                resolvedPath = PackageHelper.getSdDir(cid);
14504                resolvedFile = new File(resolvedPath);
14505            } else if (file != null) {
14506                resolvedPath = file.getAbsolutePath();
14507                resolvedFile = file;
14508            } else {
14509                resolvedPath = null;
14510                resolvedFile = null;
14511            }
14512        }
14513    }
14514
14515    static class MoveInfo {
14516        final int moveId;
14517        final String fromUuid;
14518        final String toUuid;
14519        final String packageName;
14520        final String dataAppName;
14521        final int appId;
14522        final String seinfo;
14523        final int targetSdkVersion;
14524
14525        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14526                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14527            this.moveId = moveId;
14528            this.fromUuid = fromUuid;
14529            this.toUuid = toUuid;
14530            this.packageName = packageName;
14531            this.dataAppName = dataAppName;
14532            this.appId = appId;
14533            this.seinfo = seinfo;
14534            this.targetSdkVersion = targetSdkVersion;
14535        }
14536    }
14537
14538    static class VerificationInfo {
14539        /** A constant used to indicate that a uid value is not present. */
14540        public static final int NO_UID = -1;
14541
14542        /** URI referencing where the package was downloaded from. */
14543        final Uri originatingUri;
14544
14545        /** HTTP referrer URI associated with the originatingURI. */
14546        final Uri referrer;
14547
14548        /** UID of the application that the install request originated from. */
14549        final int originatingUid;
14550
14551        /** UID of application requesting the install */
14552        final int installerUid;
14553
14554        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14555            this.originatingUri = originatingUri;
14556            this.referrer = referrer;
14557            this.originatingUid = originatingUid;
14558            this.installerUid = installerUid;
14559        }
14560    }
14561
14562    class InstallParams extends HandlerParams {
14563        final OriginInfo origin;
14564        final MoveInfo move;
14565        final IPackageInstallObserver2 observer;
14566        int installFlags;
14567        final String installerPackageName;
14568        final String volumeUuid;
14569        private InstallArgs mArgs;
14570        private int mRet;
14571        final String packageAbiOverride;
14572        final String[] grantedRuntimePermissions;
14573        final VerificationInfo verificationInfo;
14574        final Certificate[][] certificates;
14575        final int installReason;
14576
14577        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14578                int installFlags, String installerPackageName, String volumeUuid,
14579                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14580                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14581            super(user);
14582            this.origin = origin;
14583            this.move = move;
14584            this.observer = observer;
14585            this.installFlags = installFlags;
14586            this.installerPackageName = installerPackageName;
14587            this.volumeUuid = volumeUuid;
14588            this.verificationInfo = verificationInfo;
14589            this.packageAbiOverride = packageAbiOverride;
14590            this.grantedRuntimePermissions = grantedPermissions;
14591            this.certificates = certificates;
14592            this.installReason = installReason;
14593        }
14594
14595        @Override
14596        public String toString() {
14597            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14598                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14599        }
14600
14601        private int installLocationPolicy(PackageInfoLite pkgLite) {
14602            String packageName = pkgLite.packageName;
14603            int installLocation = pkgLite.installLocation;
14604            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14605            // reader
14606            synchronized (mPackages) {
14607                // Currently installed package which the new package is attempting to replace or
14608                // null if no such package is installed.
14609                PackageParser.Package installedPkg = mPackages.get(packageName);
14610                // Package which currently owns the data which the new package will own if installed.
14611                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14612                // will be null whereas dataOwnerPkg will contain information about the package
14613                // which was uninstalled while keeping its data.
14614                PackageParser.Package dataOwnerPkg = installedPkg;
14615                if (dataOwnerPkg  == null) {
14616                    PackageSetting ps = mSettings.mPackages.get(packageName);
14617                    if (ps != null) {
14618                        dataOwnerPkg = ps.pkg;
14619                    }
14620                }
14621
14622                if (dataOwnerPkg != null) {
14623                    // If installed, the package will get access to data left on the device by its
14624                    // predecessor. As a security measure, this is permited only if this is not a
14625                    // version downgrade or if the predecessor package is marked as debuggable and
14626                    // a downgrade is explicitly requested.
14627                    //
14628                    // On debuggable platform builds, downgrades are permitted even for
14629                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14630                    // not offer security guarantees and thus it's OK to disable some security
14631                    // mechanisms to make debugging/testing easier on those builds. However, even on
14632                    // debuggable builds downgrades of packages are permitted only if requested via
14633                    // installFlags. This is because we aim to keep the behavior of debuggable
14634                    // platform builds as close as possible to the behavior of non-debuggable
14635                    // platform builds.
14636                    final boolean downgradeRequested =
14637                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14638                    final boolean packageDebuggable =
14639                                (dataOwnerPkg.applicationInfo.flags
14640                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14641                    final boolean downgradePermitted =
14642                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14643                    if (!downgradePermitted) {
14644                        try {
14645                            checkDowngrade(dataOwnerPkg, pkgLite);
14646                        } catch (PackageManagerException e) {
14647                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14648                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14649                        }
14650                    }
14651                }
14652
14653                if (installedPkg != null) {
14654                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14655                        // Check for updated system application.
14656                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14657                            if (onSd) {
14658                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14659                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14660                            }
14661                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14662                        } else {
14663                            if (onSd) {
14664                                // Install flag overrides everything.
14665                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14666                            }
14667                            // If current upgrade specifies particular preference
14668                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14669                                // Application explicitly specified internal.
14670                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14671                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14672                                // App explictly prefers external. Let policy decide
14673                            } else {
14674                                // Prefer previous location
14675                                if (isExternal(installedPkg)) {
14676                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14677                                }
14678                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14679                            }
14680                        }
14681                    } else {
14682                        // Invalid install. Return error code
14683                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14684                    }
14685                }
14686            }
14687            // All the special cases have been taken care of.
14688            // Return result based on recommended install location.
14689            if (onSd) {
14690                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14691            }
14692            return pkgLite.recommendedInstallLocation;
14693        }
14694
14695        /*
14696         * Invoke remote method to get package information and install
14697         * location values. Override install location based on default
14698         * policy if needed and then create install arguments based
14699         * on the install location.
14700         */
14701        public void handleStartCopy() throws RemoteException {
14702            int ret = PackageManager.INSTALL_SUCCEEDED;
14703
14704            // If we're already staged, we've firmly committed to an install location
14705            if (origin.staged) {
14706                if (origin.file != null) {
14707                    installFlags |= PackageManager.INSTALL_INTERNAL;
14708                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14709                } else if (origin.cid != null) {
14710                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14711                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14712                } else {
14713                    throw new IllegalStateException("Invalid stage location");
14714                }
14715            }
14716
14717            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14718            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14719            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14720            PackageInfoLite pkgLite = null;
14721
14722            if (onInt && onSd) {
14723                // Check if both bits are set.
14724                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14725                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14726            } else if (onSd && ephemeral) {
14727                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14728                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14729            } else {
14730                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14731                        packageAbiOverride);
14732
14733                if (DEBUG_EPHEMERAL && ephemeral) {
14734                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14735                }
14736
14737                /*
14738                 * If we have too little free space, try to free cache
14739                 * before giving up.
14740                 */
14741                if (!origin.staged && pkgLite.recommendedInstallLocation
14742                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14743                    // TODO: focus freeing disk space on the target device
14744                    final StorageManager storage = StorageManager.from(mContext);
14745                    final long lowThreshold = storage.getStorageLowBytes(
14746                            Environment.getDataDirectory());
14747
14748                    final long sizeBytes = mContainerService.calculateInstalledSize(
14749                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14750
14751                    try {
14752                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14753                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14754                                installFlags, packageAbiOverride);
14755                    } catch (InstallerException e) {
14756                        Slog.w(TAG, "Failed to free cache", e);
14757                    }
14758
14759                    /*
14760                     * The cache free must have deleted the file we
14761                     * downloaded to install.
14762                     *
14763                     * TODO: fix the "freeCache" call to not delete
14764                     *       the file we care about.
14765                     */
14766                    if (pkgLite.recommendedInstallLocation
14767                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14768                        pkgLite.recommendedInstallLocation
14769                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14770                    }
14771                }
14772            }
14773
14774            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14775                int loc = pkgLite.recommendedInstallLocation;
14776                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14777                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14778                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14779                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14780                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14781                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14782                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14783                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14784                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14785                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14786                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14787                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14788                } else {
14789                    // Override with defaults if needed.
14790                    loc = installLocationPolicy(pkgLite);
14791                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14792                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14793                    } else if (!onSd && !onInt) {
14794                        // Override install location with flags
14795                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14796                            // Set the flag to install on external media.
14797                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14798                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14799                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14800                            if (DEBUG_EPHEMERAL) {
14801                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14802                            }
14803                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14804                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14805                                    |PackageManager.INSTALL_INTERNAL);
14806                        } else {
14807                            // Make sure the flag for installing on external
14808                            // media is unset
14809                            installFlags |= PackageManager.INSTALL_INTERNAL;
14810                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14811                        }
14812                    }
14813                }
14814            }
14815
14816            final InstallArgs args = createInstallArgs(this);
14817            mArgs = args;
14818
14819            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14820                // TODO: http://b/22976637
14821                // Apps installed for "all" users use the device owner to verify the app
14822                UserHandle verifierUser = getUser();
14823                if (verifierUser == UserHandle.ALL) {
14824                    verifierUser = UserHandle.SYSTEM;
14825                }
14826
14827                /*
14828                 * Determine if we have any installed package verifiers. If we
14829                 * do, then we'll defer to them to verify the packages.
14830                 */
14831                final int requiredUid = mRequiredVerifierPackage == null ? -1
14832                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14833                                verifierUser.getIdentifier());
14834                if (!origin.existing && requiredUid != -1
14835                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14836                    final Intent verification = new Intent(
14837                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14838                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14839                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14840                            PACKAGE_MIME_TYPE);
14841                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14842
14843                    // Query all live verifiers based on current user state
14844                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14845                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14846
14847                    if (DEBUG_VERIFY) {
14848                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14849                                + verification.toString() + " with " + pkgLite.verifiers.length
14850                                + " optional verifiers");
14851                    }
14852
14853                    final int verificationId = mPendingVerificationToken++;
14854
14855                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14856
14857                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14858                            installerPackageName);
14859
14860                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14861                            installFlags);
14862
14863                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14864                            pkgLite.packageName);
14865
14866                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14867                            pkgLite.versionCode);
14868
14869                    if (verificationInfo != null) {
14870                        if (verificationInfo.originatingUri != null) {
14871                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14872                                    verificationInfo.originatingUri);
14873                        }
14874                        if (verificationInfo.referrer != null) {
14875                            verification.putExtra(Intent.EXTRA_REFERRER,
14876                                    verificationInfo.referrer);
14877                        }
14878                        if (verificationInfo.originatingUid >= 0) {
14879                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14880                                    verificationInfo.originatingUid);
14881                        }
14882                        if (verificationInfo.installerUid >= 0) {
14883                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14884                                    verificationInfo.installerUid);
14885                        }
14886                    }
14887
14888                    final PackageVerificationState verificationState = new PackageVerificationState(
14889                            requiredUid, args);
14890
14891                    mPendingVerification.append(verificationId, verificationState);
14892
14893                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14894                            receivers, verificationState);
14895
14896                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14897                    final long idleDuration = getVerificationTimeout();
14898
14899                    /*
14900                     * If any sufficient verifiers were listed in the package
14901                     * manifest, attempt to ask them.
14902                     */
14903                    if (sufficientVerifiers != null) {
14904                        final int N = sufficientVerifiers.size();
14905                        if (N == 0) {
14906                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14907                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14908                        } else {
14909                            for (int i = 0; i < N; i++) {
14910                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14911                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14912                                        verifierComponent.getPackageName(), idleDuration,
14913                                        verifierUser.getIdentifier(), false, "package verifier");
14914
14915                                final Intent sufficientIntent = new Intent(verification);
14916                                sufficientIntent.setComponent(verifierComponent);
14917                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14918                            }
14919                        }
14920                    }
14921
14922                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14923                            mRequiredVerifierPackage, receivers);
14924                    if (ret == PackageManager.INSTALL_SUCCEEDED
14925                            && mRequiredVerifierPackage != null) {
14926                        Trace.asyncTraceBegin(
14927                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14928                        /*
14929                         * Send the intent to the required verification agent,
14930                         * but only start the verification timeout after the
14931                         * target BroadcastReceivers have run.
14932                         */
14933                        verification.setComponent(requiredVerifierComponent);
14934                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14935                                mRequiredVerifierPackage, idleDuration,
14936                                verifierUser.getIdentifier(), false, "package verifier");
14937                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14938                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14939                                new BroadcastReceiver() {
14940                                    @Override
14941                                    public void onReceive(Context context, Intent intent) {
14942                                        final Message msg = mHandler
14943                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14944                                        msg.arg1 = verificationId;
14945                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14946                                    }
14947                                }, null, 0, null, null);
14948
14949                        /*
14950                         * We don't want the copy to proceed until verification
14951                         * succeeds, so null out this field.
14952                         */
14953                        mArgs = null;
14954                    }
14955                } else {
14956                    /*
14957                     * No package verification is enabled, so immediately start
14958                     * the remote call to initiate copy using temporary file.
14959                     */
14960                    ret = args.copyApk(mContainerService, true);
14961                }
14962            }
14963
14964            mRet = ret;
14965        }
14966
14967        @Override
14968        void handleReturnCode() {
14969            // If mArgs is null, then MCS couldn't be reached. When it
14970            // reconnects, it will try again to install. At that point, this
14971            // will succeed.
14972            if (mArgs != null) {
14973                processPendingInstall(mArgs, mRet);
14974            }
14975        }
14976
14977        @Override
14978        void handleServiceError() {
14979            mArgs = createInstallArgs(this);
14980            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14981        }
14982
14983        public boolean isForwardLocked() {
14984            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14985        }
14986    }
14987
14988    /**
14989     * Used during creation of InstallArgs
14990     *
14991     * @param installFlags package installation flags
14992     * @return true if should be installed on external storage
14993     */
14994    private static boolean installOnExternalAsec(int installFlags) {
14995        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14996            return false;
14997        }
14998        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14999            return true;
15000        }
15001        return false;
15002    }
15003
15004    /**
15005     * Used during creation of InstallArgs
15006     *
15007     * @param installFlags package installation flags
15008     * @return true if should be installed as forward locked
15009     */
15010    private static boolean installForwardLocked(int installFlags) {
15011        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15012    }
15013
15014    private InstallArgs createInstallArgs(InstallParams params) {
15015        if (params.move != null) {
15016            return new MoveInstallArgs(params);
15017        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15018            return new AsecInstallArgs(params);
15019        } else {
15020            return new FileInstallArgs(params);
15021        }
15022    }
15023
15024    /**
15025     * Create args that describe an existing installed package. Typically used
15026     * when cleaning up old installs, or used as a move source.
15027     */
15028    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15029            String resourcePath, String[] instructionSets) {
15030        final boolean isInAsec;
15031        if (installOnExternalAsec(installFlags)) {
15032            /* Apps on SD card are always in ASEC containers. */
15033            isInAsec = true;
15034        } else if (installForwardLocked(installFlags)
15035                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15036            /*
15037             * Forward-locked apps are only in ASEC containers if they're the
15038             * new style
15039             */
15040            isInAsec = true;
15041        } else {
15042            isInAsec = false;
15043        }
15044
15045        if (isInAsec) {
15046            return new AsecInstallArgs(codePath, instructionSets,
15047                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15048        } else {
15049            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15050        }
15051    }
15052
15053    static abstract class InstallArgs {
15054        /** @see InstallParams#origin */
15055        final OriginInfo origin;
15056        /** @see InstallParams#move */
15057        final MoveInfo move;
15058
15059        final IPackageInstallObserver2 observer;
15060        // Always refers to PackageManager flags only
15061        final int installFlags;
15062        final String installerPackageName;
15063        final String volumeUuid;
15064        final UserHandle user;
15065        final String abiOverride;
15066        final String[] installGrantPermissions;
15067        /** If non-null, drop an async trace when the install completes */
15068        final String traceMethod;
15069        final int traceCookie;
15070        final Certificate[][] certificates;
15071        final int installReason;
15072
15073        // The list of instruction sets supported by this app. This is currently
15074        // only used during the rmdex() phase to clean up resources. We can get rid of this
15075        // if we move dex files under the common app path.
15076        /* nullable */ String[] instructionSets;
15077
15078        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15079                int installFlags, String installerPackageName, String volumeUuid,
15080                UserHandle user, String[] instructionSets,
15081                String abiOverride, String[] installGrantPermissions,
15082                String traceMethod, int traceCookie, Certificate[][] certificates,
15083                int installReason) {
15084            this.origin = origin;
15085            this.move = move;
15086            this.installFlags = installFlags;
15087            this.observer = observer;
15088            this.installerPackageName = installerPackageName;
15089            this.volumeUuid = volumeUuid;
15090            this.user = user;
15091            this.instructionSets = instructionSets;
15092            this.abiOverride = abiOverride;
15093            this.installGrantPermissions = installGrantPermissions;
15094            this.traceMethod = traceMethod;
15095            this.traceCookie = traceCookie;
15096            this.certificates = certificates;
15097            this.installReason = installReason;
15098        }
15099
15100        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15101        abstract int doPreInstall(int status);
15102
15103        /**
15104         * Rename package into final resting place. All paths on the given
15105         * scanned package should be updated to reflect the rename.
15106         */
15107        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15108        abstract int doPostInstall(int status, int uid);
15109
15110        /** @see PackageSettingBase#codePathString */
15111        abstract String getCodePath();
15112        /** @see PackageSettingBase#resourcePathString */
15113        abstract String getResourcePath();
15114
15115        // Need installer lock especially for dex file removal.
15116        abstract void cleanUpResourcesLI();
15117        abstract boolean doPostDeleteLI(boolean delete);
15118
15119        /**
15120         * Called before the source arguments are copied. This is used mostly
15121         * for MoveParams when it needs to read the source file to put it in the
15122         * destination.
15123         */
15124        int doPreCopy() {
15125            return PackageManager.INSTALL_SUCCEEDED;
15126        }
15127
15128        /**
15129         * Called after the source arguments are copied. This is used mostly for
15130         * MoveParams when it needs to read the source file to put it in the
15131         * destination.
15132         */
15133        int doPostCopy(int uid) {
15134            return PackageManager.INSTALL_SUCCEEDED;
15135        }
15136
15137        protected boolean isFwdLocked() {
15138            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15139        }
15140
15141        protected boolean isExternalAsec() {
15142            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15143        }
15144
15145        protected boolean isEphemeral() {
15146            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15147        }
15148
15149        UserHandle getUser() {
15150            return user;
15151        }
15152    }
15153
15154    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15155        if (!allCodePaths.isEmpty()) {
15156            if (instructionSets == null) {
15157                throw new IllegalStateException("instructionSet == null");
15158            }
15159            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15160            for (String codePath : allCodePaths) {
15161                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15162                    try {
15163                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15164                    } catch (InstallerException ignored) {
15165                    }
15166                }
15167            }
15168        }
15169    }
15170
15171    /**
15172     * Logic to handle installation of non-ASEC applications, including copying
15173     * and renaming logic.
15174     */
15175    class FileInstallArgs extends InstallArgs {
15176        private File codeFile;
15177        private File resourceFile;
15178
15179        // Example topology:
15180        // /data/app/com.example/base.apk
15181        // /data/app/com.example/split_foo.apk
15182        // /data/app/com.example/lib/arm/libfoo.so
15183        // /data/app/com.example/lib/arm64/libfoo.so
15184        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15185
15186        /** New install */
15187        FileInstallArgs(InstallParams params) {
15188            super(params.origin, params.move, params.observer, params.installFlags,
15189                    params.installerPackageName, params.volumeUuid,
15190                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15191                    params.grantedRuntimePermissions,
15192                    params.traceMethod, params.traceCookie, params.certificates,
15193                    params.installReason);
15194            if (isFwdLocked()) {
15195                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15196            }
15197        }
15198
15199        /** Existing install */
15200        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15201            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15202                    null, null, null, 0, null /*certificates*/,
15203                    PackageManager.INSTALL_REASON_UNKNOWN);
15204            this.codeFile = (codePath != null) ? new File(codePath) : null;
15205            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15206        }
15207
15208        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15209            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15210            try {
15211                return doCopyApk(imcs, temp);
15212            } finally {
15213                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15214            }
15215        }
15216
15217        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15218            if (origin.staged) {
15219                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15220                codeFile = origin.file;
15221                resourceFile = origin.file;
15222                return PackageManager.INSTALL_SUCCEEDED;
15223            }
15224
15225            try {
15226                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15227                final File tempDir =
15228                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15229                codeFile = tempDir;
15230                resourceFile = tempDir;
15231            } catch (IOException e) {
15232                Slog.w(TAG, "Failed to create copy file: " + e);
15233                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15234            }
15235
15236            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15237                @Override
15238                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15239                    if (!FileUtils.isValidExtFilename(name)) {
15240                        throw new IllegalArgumentException("Invalid filename: " + name);
15241                    }
15242                    try {
15243                        final File file = new File(codeFile, name);
15244                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15245                                O_RDWR | O_CREAT, 0644);
15246                        Os.chmod(file.getAbsolutePath(), 0644);
15247                        return new ParcelFileDescriptor(fd);
15248                    } catch (ErrnoException e) {
15249                        throw new RemoteException("Failed to open: " + e.getMessage());
15250                    }
15251                }
15252            };
15253
15254            int ret = PackageManager.INSTALL_SUCCEEDED;
15255            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15256            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15257                Slog.e(TAG, "Failed to copy package");
15258                return ret;
15259            }
15260
15261            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15262            NativeLibraryHelper.Handle handle = null;
15263            try {
15264                handle = NativeLibraryHelper.Handle.create(codeFile);
15265                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15266                        abiOverride);
15267            } catch (IOException e) {
15268                Slog.e(TAG, "Copying native libraries failed", e);
15269                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15270            } finally {
15271                IoUtils.closeQuietly(handle);
15272            }
15273
15274            return ret;
15275        }
15276
15277        int doPreInstall(int status) {
15278            if (status != PackageManager.INSTALL_SUCCEEDED) {
15279                cleanUp();
15280            }
15281            return status;
15282        }
15283
15284        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15285            if (status != PackageManager.INSTALL_SUCCEEDED) {
15286                cleanUp();
15287                return false;
15288            }
15289
15290            final File targetDir = codeFile.getParentFile();
15291            final File beforeCodeFile = codeFile;
15292            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15293
15294            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15295            try {
15296                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15297            } catch (ErrnoException e) {
15298                Slog.w(TAG, "Failed to rename", e);
15299                return false;
15300            }
15301
15302            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15303                Slog.w(TAG, "Failed to restorecon");
15304                return false;
15305            }
15306
15307            // Reflect the rename internally
15308            codeFile = afterCodeFile;
15309            resourceFile = afterCodeFile;
15310
15311            // Reflect the rename in scanned details
15312            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15313            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15314                    afterCodeFile, pkg.baseCodePath));
15315            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15316                    afterCodeFile, pkg.splitCodePaths));
15317
15318            // Reflect the rename in app info
15319            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15320            pkg.setApplicationInfoCodePath(pkg.codePath);
15321            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15322            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15323            pkg.setApplicationInfoResourcePath(pkg.codePath);
15324            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15325            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15326
15327            return true;
15328        }
15329
15330        int doPostInstall(int status, int uid) {
15331            if (status != PackageManager.INSTALL_SUCCEEDED) {
15332                cleanUp();
15333            }
15334            return status;
15335        }
15336
15337        @Override
15338        String getCodePath() {
15339            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15340        }
15341
15342        @Override
15343        String getResourcePath() {
15344            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15345        }
15346
15347        private boolean cleanUp() {
15348            if (codeFile == null || !codeFile.exists()) {
15349                return false;
15350            }
15351
15352            removeCodePathLI(codeFile);
15353
15354            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15355                resourceFile.delete();
15356            }
15357
15358            return true;
15359        }
15360
15361        void cleanUpResourcesLI() {
15362            // Try enumerating all code paths before deleting
15363            List<String> allCodePaths = Collections.EMPTY_LIST;
15364            if (codeFile != null && codeFile.exists()) {
15365                try {
15366                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15367                    allCodePaths = pkg.getAllCodePaths();
15368                } catch (PackageParserException e) {
15369                    // Ignored; we tried our best
15370                }
15371            }
15372
15373            cleanUp();
15374            removeDexFiles(allCodePaths, instructionSets);
15375        }
15376
15377        boolean doPostDeleteLI(boolean delete) {
15378            // XXX err, shouldn't we respect the delete flag?
15379            cleanUpResourcesLI();
15380            return true;
15381        }
15382    }
15383
15384    private boolean isAsecExternal(String cid) {
15385        final String asecPath = PackageHelper.getSdFilesystem(cid);
15386        return !asecPath.startsWith(mAsecInternalPath);
15387    }
15388
15389    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15390            PackageManagerException {
15391        if (copyRet < 0) {
15392            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15393                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15394                throw new PackageManagerException(copyRet, message);
15395            }
15396        }
15397    }
15398
15399    /**
15400     * Extract the StorageManagerService "container ID" from the full code path of an
15401     * .apk.
15402     */
15403    static String cidFromCodePath(String fullCodePath) {
15404        int eidx = fullCodePath.lastIndexOf("/");
15405        String subStr1 = fullCodePath.substring(0, eidx);
15406        int sidx = subStr1.lastIndexOf("/");
15407        return subStr1.substring(sidx+1, eidx);
15408    }
15409
15410    /**
15411     * Logic to handle installation of ASEC applications, including copying and
15412     * renaming logic.
15413     */
15414    class AsecInstallArgs extends InstallArgs {
15415        static final String RES_FILE_NAME = "pkg.apk";
15416        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15417
15418        String cid;
15419        String packagePath;
15420        String resourcePath;
15421
15422        /** New install */
15423        AsecInstallArgs(InstallParams params) {
15424            super(params.origin, params.move, params.observer, params.installFlags,
15425                    params.installerPackageName, params.volumeUuid,
15426                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15427                    params.grantedRuntimePermissions,
15428                    params.traceMethod, params.traceCookie, params.certificates,
15429                    params.installReason);
15430        }
15431
15432        /** Existing install */
15433        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15434                        boolean isExternal, boolean isForwardLocked) {
15435            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15436                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15437                    instructionSets, null, null, null, 0, null /*certificates*/,
15438                    PackageManager.INSTALL_REASON_UNKNOWN);
15439            // Hackily pretend we're still looking at a full code path
15440            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15441                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15442            }
15443
15444            // Extract cid from fullCodePath
15445            int eidx = fullCodePath.lastIndexOf("/");
15446            String subStr1 = fullCodePath.substring(0, eidx);
15447            int sidx = subStr1.lastIndexOf("/");
15448            cid = subStr1.substring(sidx+1, eidx);
15449            setMountPath(subStr1);
15450        }
15451
15452        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15453            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15454                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15455                    instructionSets, null, null, null, 0, null /*certificates*/,
15456                    PackageManager.INSTALL_REASON_UNKNOWN);
15457            this.cid = cid;
15458            setMountPath(PackageHelper.getSdDir(cid));
15459        }
15460
15461        void createCopyFile() {
15462            cid = mInstallerService.allocateExternalStageCidLegacy();
15463        }
15464
15465        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15466            if (origin.staged && origin.cid != null) {
15467                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15468                cid = origin.cid;
15469                setMountPath(PackageHelper.getSdDir(cid));
15470                return PackageManager.INSTALL_SUCCEEDED;
15471            }
15472
15473            if (temp) {
15474                createCopyFile();
15475            } else {
15476                /*
15477                 * Pre-emptively destroy the container since it's destroyed if
15478                 * copying fails due to it existing anyway.
15479                 */
15480                PackageHelper.destroySdDir(cid);
15481            }
15482
15483            final String newMountPath = imcs.copyPackageToContainer(
15484                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15485                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15486
15487            if (newMountPath != null) {
15488                setMountPath(newMountPath);
15489                return PackageManager.INSTALL_SUCCEEDED;
15490            } else {
15491                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15492            }
15493        }
15494
15495        @Override
15496        String getCodePath() {
15497            return packagePath;
15498        }
15499
15500        @Override
15501        String getResourcePath() {
15502            return resourcePath;
15503        }
15504
15505        int doPreInstall(int status) {
15506            if (status != PackageManager.INSTALL_SUCCEEDED) {
15507                // Destroy container
15508                PackageHelper.destroySdDir(cid);
15509            } else {
15510                boolean mounted = PackageHelper.isContainerMounted(cid);
15511                if (!mounted) {
15512                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15513                            Process.SYSTEM_UID);
15514                    if (newMountPath != null) {
15515                        setMountPath(newMountPath);
15516                    } else {
15517                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15518                    }
15519                }
15520            }
15521            return status;
15522        }
15523
15524        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15525            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15526            String newMountPath = null;
15527            if (PackageHelper.isContainerMounted(cid)) {
15528                // Unmount the container
15529                if (!PackageHelper.unMountSdDir(cid)) {
15530                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15531                    return false;
15532                }
15533            }
15534            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15535                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15536                        " which might be stale. Will try to clean up.");
15537                // Clean up the stale container and proceed to recreate.
15538                if (!PackageHelper.destroySdDir(newCacheId)) {
15539                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15540                    return false;
15541                }
15542                // Successfully cleaned up stale container. Try to rename again.
15543                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15544                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15545                            + " inspite of cleaning it up.");
15546                    return false;
15547                }
15548            }
15549            if (!PackageHelper.isContainerMounted(newCacheId)) {
15550                Slog.w(TAG, "Mounting container " + newCacheId);
15551                newMountPath = PackageHelper.mountSdDir(newCacheId,
15552                        getEncryptKey(), Process.SYSTEM_UID);
15553            } else {
15554                newMountPath = PackageHelper.getSdDir(newCacheId);
15555            }
15556            if (newMountPath == null) {
15557                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15558                return false;
15559            }
15560            Log.i(TAG, "Succesfully renamed " + cid +
15561                    " to " + newCacheId +
15562                    " at new path: " + newMountPath);
15563            cid = newCacheId;
15564
15565            final File beforeCodeFile = new File(packagePath);
15566            setMountPath(newMountPath);
15567            final File afterCodeFile = new File(packagePath);
15568
15569            // Reflect the rename in scanned details
15570            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15571            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15572                    afterCodeFile, pkg.baseCodePath));
15573            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15574                    afterCodeFile, pkg.splitCodePaths));
15575
15576            // Reflect the rename in app info
15577            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15578            pkg.setApplicationInfoCodePath(pkg.codePath);
15579            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15580            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15581            pkg.setApplicationInfoResourcePath(pkg.codePath);
15582            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15583            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15584
15585            return true;
15586        }
15587
15588        private void setMountPath(String mountPath) {
15589            final File mountFile = new File(mountPath);
15590
15591            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15592            if (monolithicFile.exists()) {
15593                packagePath = monolithicFile.getAbsolutePath();
15594                if (isFwdLocked()) {
15595                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15596                } else {
15597                    resourcePath = packagePath;
15598                }
15599            } else {
15600                packagePath = mountFile.getAbsolutePath();
15601                resourcePath = packagePath;
15602            }
15603        }
15604
15605        int doPostInstall(int status, int uid) {
15606            if (status != PackageManager.INSTALL_SUCCEEDED) {
15607                cleanUp();
15608            } else {
15609                final int groupOwner;
15610                final String protectedFile;
15611                if (isFwdLocked()) {
15612                    groupOwner = UserHandle.getSharedAppGid(uid);
15613                    protectedFile = RES_FILE_NAME;
15614                } else {
15615                    groupOwner = -1;
15616                    protectedFile = null;
15617                }
15618
15619                if (uid < Process.FIRST_APPLICATION_UID
15620                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15621                    Slog.e(TAG, "Failed to finalize " + cid);
15622                    PackageHelper.destroySdDir(cid);
15623                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15624                }
15625
15626                boolean mounted = PackageHelper.isContainerMounted(cid);
15627                if (!mounted) {
15628                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15629                }
15630            }
15631            return status;
15632        }
15633
15634        private void cleanUp() {
15635            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15636
15637            // Destroy secure container
15638            PackageHelper.destroySdDir(cid);
15639        }
15640
15641        private List<String> getAllCodePaths() {
15642            final File codeFile = new File(getCodePath());
15643            if (codeFile != null && codeFile.exists()) {
15644                try {
15645                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15646                    return pkg.getAllCodePaths();
15647                } catch (PackageParserException e) {
15648                    // Ignored; we tried our best
15649                }
15650            }
15651            return Collections.EMPTY_LIST;
15652        }
15653
15654        void cleanUpResourcesLI() {
15655            // Enumerate all code paths before deleting
15656            cleanUpResourcesLI(getAllCodePaths());
15657        }
15658
15659        private void cleanUpResourcesLI(List<String> allCodePaths) {
15660            cleanUp();
15661            removeDexFiles(allCodePaths, instructionSets);
15662        }
15663
15664        String getPackageName() {
15665            return getAsecPackageName(cid);
15666        }
15667
15668        boolean doPostDeleteLI(boolean delete) {
15669            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15670            final List<String> allCodePaths = getAllCodePaths();
15671            boolean mounted = PackageHelper.isContainerMounted(cid);
15672            if (mounted) {
15673                // Unmount first
15674                if (PackageHelper.unMountSdDir(cid)) {
15675                    mounted = false;
15676                }
15677            }
15678            if (!mounted && delete) {
15679                cleanUpResourcesLI(allCodePaths);
15680            }
15681            return !mounted;
15682        }
15683
15684        @Override
15685        int doPreCopy() {
15686            if (isFwdLocked()) {
15687                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15688                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15689                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15690                }
15691            }
15692
15693            return PackageManager.INSTALL_SUCCEEDED;
15694        }
15695
15696        @Override
15697        int doPostCopy(int uid) {
15698            if (isFwdLocked()) {
15699                if (uid < Process.FIRST_APPLICATION_UID
15700                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15701                                RES_FILE_NAME)) {
15702                    Slog.e(TAG, "Failed to finalize " + cid);
15703                    PackageHelper.destroySdDir(cid);
15704                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15705                }
15706            }
15707
15708            return PackageManager.INSTALL_SUCCEEDED;
15709        }
15710    }
15711
15712    /**
15713     * Logic to handle movement of existing installed applications.
15714     */
15715    class MoveInstallArgs extends InstallArgs {
15716        private File codeFile;
15717        private File resourceFile;
15718
15719        /** New install */
15720        MoveInstallArgs(InstallParams params) {
15721            super(params.origin, params.move, params.observer, params.installFlags,
15722                    params.installerPackageName, params.volumeUuid,
15723                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15724                    params.grantedRuntimePermissions,
15725                    params.traceMethod, params.traceCookie, params.certificates,
15726                    params.installReason);
15727        }
15728
15729        int copyApk(IMediaContainerService imcs, boolean temp) {
15730            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15731                    + move.fromUuid + " to " + move.toUuid);
15732            synchronized (mInstaller) {
15733                try {
15734                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15735                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15736                } catch (InstallerException e) {
15737                    Slog.w(TAG, "Failed to move app", e);
15738                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15739                }
15740            }
15741
15742            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15743            resourceFile = codeFile;
15744            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15745
15746            return PackageManager.INSTALL_SUCCEEDED;
15747        }
15748
15749        int doPreInstall(int status) {
15750            if (status != PackageManager.INSTALL_SUCCEEDED) {
15751                cleanUp(move.toUuid);
15752            }
15753            return status;
15754        }
15755
15756        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15757            if (status != PackageManager.INSTALL_SUCCEEDED) {
15758                cleanUp(move.toUuid);
15759                return false;
15760            }
15761
15762            // Reflect the move in app info
15763            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15764            pkg.setApplicationInfoCodePath(pkg.codePath);
15765            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15766            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15767            pkg.setApplicationInfoResourcePath(pkg.codePath);
15768            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15769            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15770
15771            return true;
15772        }
15773
15774        int doPostInstall(int status, int uid) {
15775            if (status == PackageManager.INSTALL_SUCCEEDED) {
15776                cleanUp(move.fromUuid);
15777            } else {
15778                cleanUp(move.toUuid);
15779            }
15780            return status;
15781        }
15782
15783        @Override
15784        String getCodePath() {
15785            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15786        }
15787
15788        @Override
15789        String getResourcePath() {
15790            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15791        }
15792
15793        private boolean cleanUp(String volumeUuid) {
15794            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15795                    move.dataAppName);
15796            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15797            final int[] userIds = sUserManager.getUserIds();
15798            synchronized (mInstallLock) {
15799                // Clean up both app data and code
15800                // All package moves are frozen until finished
15801                for (int userId : userIds) {
15802                    try {
15803                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15804                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15805                    } catch (InstallerException e) {
15806                        Slog.w(TAG, String.valueOf(e));
15807                    }
15808                }
15809                removeCodePathLI(codeFile);
15810            }
15811            return true;
15812        }
15813
15814        void cleanUpResourcesLI() {
15815            throw new UnsupportedOperationException();
15816        }
15817
15818        boolean doPostDeleteLI(boolean delete) {
15819            throw new UnsupportedOperationException();
15820        }
15821    }
15822
15823    static String getAsecPackageName(String packageCid) {
15824        int idx = packageCid.lastIndexOf("-");
15825        if (idx == -1) {
15826            return packageCid;
15827        }
15828        return packageCid.substring(0, idx);
15829    }
15830
15831    // Utility method used to create code paths based on package name and available index.
15832    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15833        String idxStr = "";
15834        int idx = 1;
15835        // Fall back to default value of idx=1 if prefix is not
15836        // part of oldCodePath
15837        if (oldCodePath != null) {
15838            String subStr = oldCodePath;
15839            // Drop the suffix right away
15840            if (suffix != null && subStr.endsWith(suffix)) {
15841                subStr = subStr.substring(0, subStr.length() - suffix.length());
15842            }
15843            // If oldCodePath already contains prefix find out the
15844            // ending index to either increment or decrement.
15845            int sidx = subStr.lastIndexOf(prefix);
15846            if (sidx != -1) {
15847                subStr = subStr.substring(sidx + prefix.length());
15848                if (subStr != null) {
15849                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15850                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15851                    }
15852                    try {
15853                        idx = Integer.parseInt(subStr);
15854                        if (idx <= 1) {
15855                            idx++;
15856                        } else {
15857                            idx--;
15858                        }
15859                    } catch(NumberFormatException e) {
15860                    }
15861                }
15862            }
15863        }
15864        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15865        return prefix + idxStr;
15866    }
15867
15868    private File getNextCodePath(File targetDir, String packageName) {
15869        File result;
15870        SecureRandom random = new SecureRandom();
15871        byte[] bytes = new byte[16];
15872        do {
15873            random.nextBytes(bytes);
15874            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15875            result = new File(targetDir, packageName + "-" + suffix);
15876        } while (result.exists());
15877        return result;
15878    }
15879
15880    // Utility method that returns the relative package path with respect
15881    // to the installation directory. Like say for /data/data/com.test-1.apk
15882    // string com.test-1 is returned.
15883    static String deriveCodePathName(String codePath) {
15884        if (codePath == null) {
15885            return null;
15886        }
15887        final File codeFile = new File(codePath);
15888        final String name = codeFile.getName();
15889        if (codeFile.isDirectory()) {
15890            return name;
15891        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15892            final int lastDot = name.lastIndexOf('.');
15893            return name.substring(0, lastDot);
15894        } else {
15895            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15896            return null;
15897        }
15898    }
15899
15900    static class PackageInstalledInfo {
15901        String name;
15902        int uid;
15903        // The set of users that originally had this package installed.
15904        int[] origUsers;
15905        // The set of users that now have this package installed.
15906        int[] newUsers;
15907        PackageParser.Package pkg;
15908        int returnCode;
15909        String returnMsg;
15910        PackageRemovedInfo removedInfo;
15911        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15912
15913        public void setError(int code, String msg) {
15914            setReturnCode(code);
15915            setReturnMessage(msg);
15916            Slog.w(TAG, msg);
15917        }
15918
15919        public void setError(String msg, PackageParserException e) {
15920            setReturnCode(e.error);
15921            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15922            Slog.w(TAG, msg, e);
15923        }
15924
15925        public void setError(String msg, PackageManagerException e) {
15926            returnCode = e.error;
15927            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15928            Slog.w(TAG, msg, e);
15929        }
15930
15931        public void setReturnCode(int returnCode) {
15932            this.returnCode = returnCode;
15933            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15934            for (int i = 0; i < childCount; i++) {
15935                addedChildPackages.valueAt(i).returnCode = returnCode;
15936            }
15937        }
15938
15939        private void setReturnMessage(String returnMsg) {
15940            this.returnMsg = returnMsg;
15941            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15942            for (int i = 0; i < childCount; i++) {
15943                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15944            }
15945        }
15946
15947        // In some error cases we want to convey more info back to the observer
15948        String origPackage;
15949        String origPermission;
15950    }
15951
15952    /*
15953     * Install a non-existing package.
15954     */
15955    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15956            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15957            PackageInstalledInfo res, int installReason) {
15958        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15959
15960        // Remember this for later, in case we need to rollback this install
15961        String pkgName = pkg.packageName;
15962
15963        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15964
15965        synchronized(mPackages) {
15966            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15967            if (renamedPackage != null) {
15968                // A package with the same name is already installed, though
15969                // it has been renamed to an older name.  The package we
15970                // are trying to install should be installed as an update to
15971                // the existing one, but that has not been requested, so bail.
15972                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15973                        + " without first uninstalling package running as "
15974                        + renamedPackage);
15975                return;
15976            }
15977            if (mPackages.containsKey(pkgName)) {
15978                // Don't allow installation over an existing package with the same name.
15979                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15980                        + " without first uninstalling.");
15981                return;
15982            }
15983        }
15984
15985        try {
15986            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15987                    System.currentTimeMillis(), user);
15988
15989            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15990
15991            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15992                prepareAppDataAfterInstallLIF(newPackage);
15993
15994            } else {
15995                // Remove package from internal structures, but keep around any
15996                // data that might have already existed
15997                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15998                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15999            }
16000        } catch (PackageManagerException e) {
16001            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16002        }
16003
16004        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16005    }
16006
16007    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16008        // Can't rotate keys during boot or if sharedUser.
16009        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16010                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16011            return false;
16012        }
16013        // app is using upgradeKeySets; make sure all are valid
16014        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16015        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16016        for (int i = 0; i < upgradeKeySets.length; i++) {
16017            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16018                Slog.wtf(TAG, "Package "
16019                         + (oldPs.name != null ? oldPs.name : "<null>")
16020                         + " contains upgrade-key-set reference to unknown key-set: "
16021                         + upgradeKeySets[i]
16022                         + " reverting to signatures check.");
16023                return false;
16024            }
16025        }
16026        return true;
16027    }
16028
16029    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16030        // Upgrade keysets are being used.  Determine if new package has a superset of the
16031        // required keys.
16032        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16033        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16034        for (int i = 0; i < upgradeKeySets.length; i++) {
16035            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16036            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16037                return true;
16038            }
16039        }
16040        return false;
16041    }
16042
16043    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16044        try (DigestInputStream digestStream =
16045                new DigestInputStream(new FileInputStream(file), digest)) {
16046            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16047        }
16048    }
16049
16050    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16051            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16052            int installReason) {
16053        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16054
16055        final PackageParser.Package oldPackage;
16056        final String pkgName = pkg.packageName;
16057        final int[] allUsers;
16058        final int[] installedUsers;
16059
16060        synchronized(mPackages) {
16061            oldPackage = mPackages.get(pkgName);
16062            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16063
16064            // don't allow upgrade to target a release SDK from a pre-release SDK
16065            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16066                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16067            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16068                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16069            if (oldTargetsPreRelease
16070                    && !newTargetsPreRelease
16071                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16072                Slog.w(TAG, "Can't install package targeting released sdk");
16073                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16074                return;
16075            }
16076
16077            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16078
16079            // verify signatures are valid
16080            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16081                if (!checkUpgradeKeySetLP(ps, pkg)) {
16082                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16083                            "New package not signed by keys specified by upgrade-keysets: "
16084                                    + pkgName);
16085                    return;
16086                }
16087            } else {
16088                // default to original signature matching
16089                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16090                        != PackageManager.SIGNATURE_MATCH) {
16091                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16092                            "New package has a different signature: " + pkgName);
16093                    return;
16094                }
16095            }
16096
16097            // don't allow a system upgrade unless the upgrade hash matches
16098            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16099                byte[] digestBytes = null;
16100                try {
16101                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16102                    updateDigest(digest, new File(pkg.baseCodePath));
16103                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16104                        for (String path : pkg.splitCodePaths) {
16105                            updateDigest(digest, new File(path));
16106                        }
16107                    }
16108                    digestBytes = digest.digest();
16109                } catch (NoSuchAlgorithmException | IOException e) {
16110                    res.setError(INSTALL_FAILED_INVALID_APK,
16111                            "Could not compute hash: " + pkgName);
16112                    return;
16113                }
16114                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16115                    res.setError(INSTALL_FAILED_INVALID_APK,
16116                            "New package fails restrict-update check: " + pkgName);
16117                    return;
16118                }
16119                // retain upgrade restriction
16120                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16121            }
16122
16123            // Check for shared user id changes
16124            String invalidPackageName =
16125                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16126            if (invalidPackageName != null) {
16127                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16128                        "Package " + invalidPackageName + " tried to change user "
16129                                + oldPackage.mSharedUserId);
16130                return;
16131            }
16132
16133            // In case of rollback, remember per-user/profile install state
16134            allUsers = sUserManager.getUserIds();
16135            installedUsers = ps.queryInstalledUsers(allUsers, true);
16136
16137            // don't allow an upgrade from full to ephemeral
16138            if (isInstantApp) {
16139                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16140                    for (int currentUser : allUsers) {
16141                        if (!ps.getInstantApp(currentUser)) {
16142                            // can't downgrade from full to instant
16143                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16144                                    + " for user: " + currentUser);
16145                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16146                            return;
16147                        }
16148                    }
16149                } else if (!ps.getInstantApp(user.getIdentifier())) {
16150                    // can't downgrade from full to instant
16151                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16152                            + " for user: " + user.getIdentifier());
16153                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16154                    return;
16155                }
16156            }
16157        }
16158
16159        // Update what is removed
16160        res.removedInfo = new PackageRemovedInfo(this);
16161        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16162        res.removedInfo.removedPackage = oldPackage.packageName;
16163        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16164        res.removedInfo.isUpdate = true;
16165        res.removedInfo.origUsers = installedUsers;
16166        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
16167        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16168        for (int i = 0; i < installedUsers.length; i++) {
16169            final int userId = installedUsers[i];
16170            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16171        }
16172
16173        final int childCount = (oldPackage.childPackages != null)
16174                ? oldPackage.childPackages.size() : 0;
16175        for (int i = 0; i < childCount; i++) {
16176            boolean childPackageUpdated = false;
16177            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16178            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16179            if (res.addedChildPackages != null) {
16180                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16181                if (childRes != null) {
16182                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16183                    childRes.removedInfo.removedPackage = childPkg.packageName;
16184                    childRes.removedInfo.isUpdate = true;
16185                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16186                    childPackageUpdated = true;
16187                }
16188            }
16189            if (!childPackageUpdated) {
16190                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16191                childRemovedRes.removedPackage = childPkg.packageName;
16192                childRemovedRes.isUpdate = false;
16193                childRemovedRes.dataRemoved = true;
16194                synchronized (mPackages) {
16195                    if (childPs != null) {
16196                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16197                    }
16198                }
16199                if (res.removedInfo.removedChildPackages == null) {
16200                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16201                }
16202                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16203            }
16204        }
16205
16206        boolean sysPkg = (isSystemApp(oldPackage));
16207        if (sysPkg) {
16208            // Set the system/privileged flags as needed
16209            final boolean privileged =
16210                    (oldPackage.applicationInfo.privateFlags
16211                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16212            final int systemPolicyFlags = policyFlags
16213                    | PackageParser.PARSE_IS_SYSTEM
16214                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16215
16216            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16217                    user, allUsers, installerPackageName, res, installReason);
16218        } else {
16219            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16220                    user, allUsers, installerPackageName, res, installReason);
16221        }
16222    }
16223
16224    public List<String> getPreviousCodePaths(String packageName) {
16225        final PackageSetting ps = mSettings.mPackages.get(packageName);
16226        final List<String> result = new ArrayList<String>();
16227        if (ps != null && ps.oldCodePaths != null) {
16228            result.addAll(ps.oldCodePaths);
16229        }
16230        return result;
16231    }
16232
16233    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16234            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16235            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16236            int installReason) {
16237        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16238                + deletedPackage);
16239
16240        String pkgName = deletedPackage.packageName;
16241        boolean deletedPkg = true;
16242        boolean addedPkg = false;
16243        boolean updatedSettings = false;
16244        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16245        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16246                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16247
16248        final long origUpdateTime = (pkg.mExtras != null)
16249                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16250
16251        // First delete the existing package while retaining the data directory
16252        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16253                res.removedInfo, true, pkg)) {
16254            // If the existing package wasn't successfully deleted
16255            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16256            deletedPkg = false;
16257        } else {
16258            // Successfully deleted the old package; proceed with replace.
16259
16260            // If deleted package lived in a container, give users a chance to
16261            // relinquish resources before killing.
16262            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16263                if (DEBUG_INSTALL) {
16264                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16265                }
16266                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16267                final ArrayList<String> pkgList = new ArrayList<String>(1);
16268                pkgList.add(deletedPackage.applicationInfo.packageName);
16269                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16270            }
16271
16272            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16273                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16274            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16275
16276            try {
16277                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16278                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16279                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16280                        installReason);
16281
16282                // Update the in-memory copy of the previous code paths.
16283                PackageSetting ps = mSettings.mPackages.get(pkgName);
16284                if (!killApp) {
16285                    if (ps.oldCodePaths == null) {
16286                        ps.oldCodePaths = new ArraySet<>();
16287                    }
16288                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16289                    if (deletedPackage.splitCodePaths != null) {
16290                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16291                    }
16292                } else {
16293                    ps.oldCodePaths = null;
16294                }
16295                if (ps.childPackageNames != null) {
16296                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16297                        final String childPkgName = ps.childPackageNames.get(i);
16298                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16299                        childPs.oldCodePaths = ps.oldCodePaths;
16300                    }
16301                }
16302                // set instant app status, but, only if it's explicitly specified
16303                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16304                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16305                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16306                prepareAppDataAfterInstallLIF(newPackage);
16307                addedPkg = true;
16308                mDexManager.notifyPackageUpdated(newPackage.packageName,
16309                        newPackage.baseCodePath, newPackage.splitCodePaths);
16310            } catch (PackageManagerException e) {
16311                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16312            }
16313        }
16314
16315        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16316            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16317
16318            // Revert all internal state mutations and added folders for the failed install
16319            if (addedPkg) {
16320                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16321                        res.removedInfo, true, null);
16322            }
16323
16324            // Restore the old package
16325            if (deletedPkg) {
16326                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16327                File restoreFile = new File(deletedPackage.codePath);
16328                // Parse old package
16329                boolean oldExternal = isExternal(deletedPackage);
16330                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16331                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16332                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16333                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16334                try {
16335                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16336                            null);
16337                } catch (PackageManagerException e) {
16338                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16339                            + e.getMessage());
16340                    return;
16341                }
16342
16343                synchronized (mPackages) {
16344                    // Ensure the installer package name up to date
16345                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16346
16347                    // Update permissions for restored package
16348                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16349
16350                    mSettings.writeLPr();
16351                }
16352
16353                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16354            }
16355        } else {
16356            synchronized (mPackages) {
16357                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16358                if (ps != null) {
16359                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16360                    if (res.removedInfo.removedChildPackages != null) {
16361                        final int childCount = res.removedInfo.removedChildPackages.size();
16362                        // Iterate in reverse as we may modify the collection
16363                        for (int i = childCount - 1; i >= 0; i--) {
16364                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16365                            if (res.addedChildPackages.containsKey(childPackageName)) {
16366                                res.removedInfo.removedChildPackages.removeAt(i);
16367                            } else {
16368                                PackageRemovedInfo childInfo = res.removedInfo
16369                                        .removedChildPackages.valueAt(i);
16370                                childInfo.removedForAllUsers = mPackages.get(
16371                                        childInfo.removedPackage) == null;
16372                            }
16373                        }
16374                    }
16375                }
16376            }
16377        }
16378    }
16379
16380    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16381            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16382            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16383            int installReason) {
16384        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16385                + ", old=" + deletedPackage);
16386
16387        final boolean disabledSystem;
16388
16389        // Remove existing system package
16390        removePackageLI(deletedPackage, true);
16391
16392        synchronized (mPackages) {
16393            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16394        }
16395        if (!disabledSystem) {
16396            // We didn't need to disable the .apk as a current system package,
16397            // which means we are replacing another update that is already
16398            // installed.  We need to make sure to delete the older one's .apk.
16399            res.removedInfo.args = createInstallArgsForExisting(0,
16400                    deletedPackage.applicationInfo.getCodePath(),
16401                    deletedPackage.applicationInfo.getResourcePath(),
16402                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16403        } else {
16404            res.removedInfo.args = null;
16405        }
16406
16407        // Successfully disabled the old package. Now proceed with re-installation
16408        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16409                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16410        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16411
16412        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16413        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16414                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16415
16416        PackageParser.Package newPackage = null;
16417        try {
16418            // Add the package to the internal data structures
16419            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16420
16421            // Set the update and install times
16422            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16423            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16424                    System.currentTimeMillis());
16425
16426            // Update the package dynamic state if succeeded
16427            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16428                // Now that the install succeeded make sure we remove data
16429                // directories for any child package the update removed.
16430                final int deletedChildCount = (deletedPackage.childPackages != null)
16431                        ? deletedPackage.childPackages.size() : 0;
16432                final int newChildCount = (newPackage.childPackages != null)
16433                        ? newPackage.childPackages.size() : 0;
16434                for (int i = 0; i < deletedChildCount; i++) {
16435                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16436                    boolean childPackageDeleted = true;
16437                    for (int j = 0; j < newChildCount; j++) {
16438                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16439                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16440                            childPackageDeleted = false;
16441                            break;
16442                        }
16443                    }
16444                    if (childPackageDeleted) {
16445                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16446                                deletedChildPkg.packageName);
16447                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16448                            PackageRemovedInfo removedChildRes = res.removedInfo
16449                                    .removedChildPackages.get(deletedChildPkg.packageName);
16450                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16451                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16452                        }
16453                    }
16454                }
16455
16456                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16457                        installReason);
16458                prepareAppDataAfterInstallLIF(newPackage);
16459
16460                mDexManager.notifyPackageUpdated(newPackage.packageName,
16461                            newPackage.baseCodePath, newPackage.splitCodePaths);
16462            }
16463        } catch (PackageManagerException e) {
16464            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16465            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16466        }
16467
16468        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16469            // Re installation failed. Restore old information
16470            // Remove new pkg information
16471            if (newPackage != null) {
16472                removeInstalledPackageLI(newPackage, true);
16473            }
16474            // Add back the old system package
16475            try {
16476                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16477            } catch (PackageManagerException e) {
16478                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16479            }
16480
16481            synchronized (mPackages) {
16482                if (disabledSystem) {
16483                    enableSystemPackageLPw(deletedPackage);
16484                }
16485
16486                // Ensure the installer package name up to date
16487                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16488
16489                // Update permissions for restored package
16490                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16491
16492                mSettings.writeLPr();
16493            }
16494
16495            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16496                    + " after failed upgrade");
16497        }
16498    }
16499
16500    /**
16501     * Checks whether the parent or any of the child packages have a change shared
16502     * user. For a package to be a valid update the shred users of the parent and
16503     * the children should match. We may later support changing child shared users.
16504     * @param oldPkg The updated package.
16505     * @param newPkg The update package.
16506     * @return The shared user that change between the versions.
16507     */
16508    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16509            PackageParser.Package newPkg) {
16510        // Check parent shared user
16511        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16512            return newPkg.packageName;
16513        }
16514        // Check child shared users
16515        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16516        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16517        for (int i = 0; i < newChildCount; i++) {
16518            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16519            // If this child was present, did it have the same shared user?
16520            for (int j = 0; j < oldChildCount; j++) {
16521                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16522                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16523                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16524                    return newChildPkg.packageName;
16525                }
16526            }
16527        }
16528        return null;
16529    }
16530
16531    private void removeNativeBinariesLI(PackageSetting ps) {
16532        // Remove the lib path for the parent package
16533        if (ps != null) {
16534            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16535            // Remove the lib path for the child packages
16536            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16537            for (int i = 0; i < childCount; i++) {
16538                PackageSetting childPs = null;
16539                synchronized (mPackages) {
16540                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16541                }
16542                if (childPs != null) {
16543                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16544                            .legacyNativeLibraryPathString);
16545                }
16546            }
16547        }
16548    }
16549
16550    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16551        // Enable the parent package
16552        mSettings.enableSystemPackageLPw(pkg.packageName);
16553        // Enable the child packages
16554        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16555        for (int i = 0; i < childCount; i++) {
16556            PackageParser.Package childPkg = pkg.childPackages.get(i);
16557            mSettings.enableSystemPackageLPw(childPkg.packageName);
16558        }
16559    }
16560
16561    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16562            PackageParser.Package newPkg) {
16563        // Disable the parent package (parent always replaced)
16564        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16565        // Disable the child packages
16566        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16567        for (int i = 0; i < childCount; i++) {
16568            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16569            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16570            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16571        }
16572        return disabled;
16573    }
16574
16575    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16576            String installerPackageName) {
16577        // Enable the parent package
16578        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16579        // Enable the child packages
16580        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16581        for (int i = 0; i < childCount; i++) {
16582            PackageParser.Package childPkg = pkg.childPackages.get(i);
16583            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16584        }
16585    }
16586
16587    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16588        // Collect all used permissions in the UID
16589        ArraySet<String> usedPermissions = new ArraySet<>();
16590        final int packageCount = su.packages.size();
16591        for (int i = 0; i < packageCount; i++) {
16592            PackageSetting ps = su.packages.valueAt(i);
16593            if (ps.pkg == null) {
16594                continue;
16595            }
16596            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16597            for (int j = 0; j < requestedPermCount; j++) {
16598                String permission = ps.pkg.requestedPermissions.get(j);
16599                BasePermission bp = mSettings.mPermissions.get(permission);
16600                if (bp != null) {
16601                    usedPermissions.add(permission);
16602                }
16603            }
16604        }
16605
16606        PermissionsState permissionsState = su.getPermissionsState();
16607        // Prune install permissions
16608        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16609        final int installPermCount = installPermStates.size();
16610        for (int i = installPermCount - 1; i >= 0;  i--) {
16611            PermissionState permissionState = installPermStates.get(i);
16612            if (!usedPermissions.contains(permissionState.getName())) {
16613                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16614                if (bp != null) {
16615                    permissionsState.revokeInstallPermission(bp);
16616                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16617                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16618                }
16619            }
16620        }
16621
16622        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16623
16624        // Prune runtime permissions
16625        for (int userId : allUserIds) {
16626            List<PermissionState> runtimePermStates = permissionsState
16627                    .getRuntimePermissionStates(userId);
16628            final int runtimePermCount = runtimePermStates.size();
16629            for (int i = runtimePermCount - 1; i >= 0; i--) {
16630                PermissionState permissionState = runtimePermStates.get(i);
16631                if (!usedPermissions.contains(permissionState.getName())) {
16632                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16633                    if (bp != null) {
16634                        permissionsState.revokeRuntimePermission(bp, userId);
16635                        permissionsState.updatePermissionFlags(bp, userId,
16636                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16637                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16638                                runtimePermissionChangedUserIds, userId);
16639                    }
16640                }
16641            }
16642        }
16643
16644        return runtimePermissionChangedUserIds;
16645    }
16646
16647    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16648            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16649        // Update the parent package setting
16650        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16651                res, user, installReason);
16652        // Update the child packages setting
16653        final int childCount = (newPackage.childPackages != null)
16654                ? newPackage.childPackages.size() : 0;
16655        for (int i = 0; i < childCount; i++) {
16656            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16657            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16658            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16659                    childRes.origUsers, childRes, user, installReason);
16660        }
16661    }
16662
16663    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16664            String installerPackageName, int[] allUsers, int[] installedForUsers,
16665            PackageInstalledInfo res, UserHandle user, int installReason) {
16666        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16667
16668        String pkgName = newPackage.packageName;
16669        synchronized (mPackages) {
16670            //write settings. the installStatus will be incomplete at this stage.
16671            //note that the new package setting would have already been
16672            //added to mPackages. It hasn't been persisted yet.
16673            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16674            // TODO: Remove this write? It's also written at the end of this method
16675            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16676            mSettings.writeLPr();
16677            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16678        }
16679
16680        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16681        synchronized (mPackages) {
16682            updatePermissionsLPw(newPackage.packageName, newPackage,
16683                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16684                            ? UPDATE_PERMISSIONS_ALL : 0));
16685            // For system-bundled packages, we assume that installing an upgraded version
16686            // of the package implies that the user actually wants to run that new code,
16687            // so we enable the package.
16688            PackageSetting ps = mSettings.mPackages.get(pkgName);
16689            final int userId = user.getIdentifier();
16690            if (ps != null) {
16691                if (isSystemApp(newPackage)) {
16692                    if (DEBUG_INSTALL) {
16693                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16694                    }
16695                    // Enable system package for requested users
16696                    if (res.origUsers != null) {
16697                        for (int origUserId : res.origUsers) {
16698                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16699                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16700                                        origUserId, installerPackageName);
16701                            }
16702                        }
16703                    }
16704                    // Also convey the prior install/uninstall state
16705                    if (allUsers != null && installedForUsers != null) {
16706                        for (int currentUserId : allUsers) {
16707                            final boolean installed = ArrayUtils.contains(
16708                                    installedForUsers, currentUserId);
16709                            if (DEBUG_INSTALL) {
16710                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16711                            }
16712                            ps.setInstalled(installed, currentUserId);
16713                        }
16714                        // these install state changes will be persisted in the
16715                        // upcoming call to mSettings.writeLPr().
16716                    }
16717                }
16718                // It's implied that when a user requests installation, they want the app to be
16719                // installed and enabled.
16720                if (userId != UserHandle.USER_ALL) {
16721                    ps.setInstalled(true, userId);
16722                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16723                }
16724
16725                // When replacing an existing package, preserve the original install reason for all
16726                // users that had the package installed before.
16727                final Set<Integer> previousUserIds = new ArraySet<>();
16728                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16729                    final int installReasonCount = res.removedInfo.installReasons.size();
16730                    for (int i = 0; i < installReasonCount; i++) {
16731                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16732                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16733                        ps.setInstallReason(previousInstallReason, previousUserId);
16734                        previousUserIds.add(previousUserId);
16735                    }
16736                }
16737
16738                // Set install reason for users that are having the package newly installed.
16739                if (userId == UserHandle.USER_ALL) {
16740                    for (int currentUserId : sUserManager.getUserIds()) {
16741                        if (!previousUserIds.contains(currentUserId)) {
16742                            ps.setInstallReason(installReason, currentUserId);
16743                        }
16744                    }
16745                } else if (!previousUserIds.contains(userId)) {
16746                    ps.setInstallReason(installReason, userId);
16747                }
16748                mSettings.writeKernelMappingLPr(ps);
16749            }
16750            res.name = pkgName;
16751            res.uid = newPackage.applicationInfo.uid;
16752            res.pkg = newPackage;
16753            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16754            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16755            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16756            //to update install status
16757            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16758            mSettings.writeLPr();
16759            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16760        }
16761
16762        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16763    }
16764
16765    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16766        try {
16767            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16768            installPackageLI(args, res);
16769        } finally {
16770            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16771        }
16772    }
16773
16774    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16775        final int installFlags = args.installFlags;
16776        final String installerPackageName = args.installerPackageName;
16777        final String volumeUuid = args.volumeUuid;
16778        final File tmpPackageFile = new File(args.getCodePath());
16779        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16780        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16781                || (args.volumeUuid != null));
16782        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16783        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16784        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16785        boolean replace = false;
16786        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16787        if (args.move != null) {
16788            // moving a complete application; perform an initial scan on the new install location
16789            scanFlags |= SCAN_INITIAL;
16790        }
16791        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16792            scanFlags |= SCAN_DONT_KILL_APP;
16793        }
16794        if (instantApp) {
16795            scanFlags |= SCAN_AS_INSTANT_APP;
16796        }
16797        if (fullApp) {
16798            scanFlags |= SCAN_AS_FULL_APP;
16799        }
16800
16801        // Result object to be returned
16802        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16803
16804        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16805
16806        // Sanity check
16807        if (instantApp && (forwardLocked || onExternal)) {
16808            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16809                    + " external=" + onExternal);
16810            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16811            return;
16812        }
16813
16814        // Retrieve PackageSettings and parse package
16815        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16816                | PackageParser.PARSE_ENFORCE_CODE
16817                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16818                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16819                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16820                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16821        PackageParser pp = new PackageParser();
16822        pp.setSeparateProcesses(mSeparateProcesses);
16823        pp.setDisplayMetrics(mMetrics);
16824        pp.setCallback(mPackageParserCallback);
16825
16826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16827        final PackageParser.Package pkg;
16828        try {
16829            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16830        } catch (PackageParserException e) {
16831            res.setError("Failed parse during installPackageLI", e);
16832            return;
16833        } finally {
16834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16835        }
16836
16837        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16838        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16839            Slog.w(TAG, "Instant app package " + pkg.packageName
16840                    + " does not target O, this will be a fatal error.");
16841            // STOPSHIP: Make this a fatal error
16842            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16843        }
16844        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16845            Slog.w(TAG, "Instant app package " + pkg.packageName
16846                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16847            // STOPSHIP: Make this a fatal error
16848            pkg.applicationInfo.targetSandboxVersion = 2;
16849        }
16850
16851        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16852            // Static shared libraries have synthetic package names
16853            renameStaticSharedLibraryPackage(pkg);
16854
16855            // No static shared libs on external storage
16856            if (onExternal) {
16857                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16858                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16859                        "Packages declaring static-shared libs cannot be updated");
16860                return;
16861            }
16862        }
16863
16864        // If we are installing a clustered package add results for the children
16865        if (pkg.childPackages != null) {
16866            synchronized (mPackages) {
16867                final int childCount = pkg.childPackages.size();
16868                for (int i = 0; i < childCount; i++) {
16869                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16870                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16871                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16872                    childRes.pkg = childPkg;
16873                    childRes.name = childPkg.packageName;
16874                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16875                    if (childPs != null) {
16876                        childRes.origUsers = childPs.queryInstalledUsers(
16877                                sUserManager.getUserIds(), true);
16878                    }
16879                    if ((mPackages.containsKey(childPkg.packageName))) {
16880                        childRes.removedInfo = new PackageRemovedInfo(this);
16881                        childRes.removedInfo.removedPackage = childPkg.packageName;
16882                    }
16883                    if (res.addedChildPackages == null) {
16884                        res.addedChildPackages = new ArrayMap<>();
16885                    }
16886                    res.addedChildPackages.put(childPkg.packageName, childRes);
16887                }
16888            }
16889        }
16890
16891        // If package doesn't declare API override, mark that we have an install
16892        // time CPU ABI override.
16893        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16894            pkg.cpuAbiOverride = args.abiOverride;
16895        }
16896
16897        String pkgName = res.name = pkg.packageName;
16898        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16899            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16900                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16901                return;
16902            }
16903        }
16904
16905        try {
16906            // either use what we've been given or parse directly from the APK
16907            if (args.certificates != null) {
16908                try {
16909                    PackageParser.populateCertificates(pkg, args.certificates);
16910                } catch (PackageParserException e) {
16911                    // there was something wrong with the certificates we were given;
16912                    // try to pull them from the APK
16913                    PackageParser.collectCertificates(pkg, parseFlags);
16914                }
16915            } else {
16916                PackageParser.collectCertificates(pkg, parseFlags);
16917            }
16918        } catch (PackageParserException e) {
16919            res.setError("Failed collect during installPackageLI", e);
16920            return;
16921        }
16922
16923        // Get rid of all references to package scan path via parser.
16924        pp = null;
16925        String oldCodePath = null;
16926        boolean systemApp = false;
16927        synchronized (mPackages) {
16928            // Check if installing already existing package
16929            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16930                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16931                if (pkg.mOriginalPackages != null
16932                        && pkg.mOriginalPackages.contains(oldName)
16933                        && mPackages.containsKey(oldName)) {
16934                    // This package is derived from an original package,
16935                    // and this device has been updating from that original
16936                    // name.  We must continue using the original name, so
16937                    // rename the new package here.
16938                    pkg.setPackageName(oldName);
16939                    pkgName = pkg.packageName;
16940                    replace = true;
16941                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16942                            + oldName + " pkgName=" + pkgName);
16943                } else if (mPackages.containsKey(pkgName)) {
16944                    // This package, under its official name, already exists
16945                    // on the device; we should replace it.
16946                    replace = true;
16947                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16948                }
16949
16950                // Child packages are installed through the parent package
16951                if (pkg.parentPackage != null) {
16952                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16953                            "Package " + pkg.packageName + " is child of package "
16954                                    + pkg.parentPackage.parentPackage + ". Child packages "
16955                                    + "can be updated only through the parent package.");
16956                    return;
16957                }
16958
16959                if (replace) {
16960                    // Prevent apps opting out from runtime permissions
16961                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16962                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16963                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16964                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16965                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16966                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16967                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16968                                        + " doesn't support runtime permissions but the old"
16969                                        + " target SDK " + oldTargetSdk + " does.");
16970                        return;
16971                    }
16972                    // Prevent apps from downgrading their targetSandbox.
16973                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16974                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16975                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16976                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16977                                "Package " + pkg.packageName + " new target sandbox "
16978                                + newTargetSandbox + " is incompatible with the previous value of"
16979                                + oldTargetSandbox + ".");
16980                        return;
16981                    }
16982
16983                    // Prevent installing of child packages
16984                    if (oldPackage.parentPackage != null) {
16985                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16986                                "Package " + pkg.packageName + " is child of package "
16987                                        + oldPackage.parentPackage + ". Child packages "
16988                                        + "can be updated only through the parent package.");
16989                        return;
16990                    }
16991                }
16992            }
16993
16994            PackageSetting ps = mSettings.mPackages.get(pkgName);
16995            if (ps != null) {
16996                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16997
16998                // Static shared libs have same package with different versions where
16999                // we internally use a synthetic package name to allow multiple versions
17000                // of the same package, therefore we need to compare signatures against
17001                // the package setting for the latest library version.
17002                PackageSetting signatureCheckPs = ps;
17003                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17004                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17005                    if (libraryEntry != null) {
17006                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17007                    }
17008                }
17009
17010                // Quick sanity check that we're signed correctly if updating;
17011                // we'll check this again later when scanning, but we want to
17012                // bail early here before tripping over redefined permissions.
17013                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17014                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17015                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17016                                + pkg.packageName + " upgrade keys do not match the "
17017                                + "previously installed version");
17018                        return;
17019                    }
17020                } else {
17021                    try {
17022                        verifySignaturesLP(signatureCheckPs, pkg);
17023                    } catch (PackageManagerException e) {
17024                        res.setError(e.error, e.getMessage());
17025                        return;
17026                    }
17027                }
17028
17029                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17030                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17031                    systemApp = (ps.pkg.applicationInfo.flags &
17032                            ApplicationInfo.FLAG_SYSTEM) != 0;
17033                }
17034                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17035            }
17036
17037            int N = pkg.permissions.size();
17038            for (int i = N-1; i >= 0; i--) {
17039                PackageParser.Permission perm = pkg.permissions.get(i);
17040                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17041
17042                // Don't allow anyone but the platform to define ephemeral permissions.
17043                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17044                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17045                    Slog.w(TAG, "Package " + pkg.packageName
17046                            + " attempting to delcare ephemeral permission "
17047                            + perm.info.name + "; Removing ephemeral.");
17048                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17049                }
17050                // Check whether the newly-scanned package wants to define an already-defined perm
17051                if (bp != null) {
17052                    // If the defining package is signed with our cert, it's okay.  This
17053                    // also includes the "updating the same package" case, of course.
17054                    // "updating same package" could also involve key-rotation.
17055                    final boolean sigsOk;
17056                    if (bp.sourcePackage.equals(pkg.packageName)
17057                            && (bp.packageSetting instanceof PackageSetting)
17058                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17059                                    scanFlags))) {
17060                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17061                    } else {
17062                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17063                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17064                    }
17065                    if (!sigsOk) {
17066                        // If the owning package is the system itself, we log but allow
17067                        // install to proceed; we fail the install on all other permission
17068                        // redefinitions.
17069                        if (!bp.sourcePackage.equals("android")) {
17070                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17071                                    + pkg.packageName + " attempting to redeclare permission "
17072                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17073                            res.origPermission = perm.info.name;
17074                            res.origPackage = bp.sourcePackage;
17075                            return;
17076                        } else {
17077                            Slog.w(TAG, "Package " + pkg.packageName
17078                                    + " attempting to redeclare system permission "
17079                                    + perm.info.name + "; ignoring new declaration");
17080                            pkg.permissions.remove(i);
17081                        }
17082                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17083                        // Prevent apps to change protection level to dangerous from any other
17084                        // type as this would allow a privilege escalation where an app adds a
17085                        // normal/signature permission in other app's group and later redefines
17086                        // it as dangerous leading to the group auto-grant.
17087                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17088                                == PermissionInfo.PROTECTION_DANGEROUS) {
17089                            if (bp != null && !bp.isRuntime()) {
17090                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17091                                        + "non-runtime permission " + perm.info.name
17092                                        + " to runtime; keeping old protection level");
17093                                perm.info.protectionLevel = bp.protectionLevel;
17094                            }
17095                        }
17096                    }
17097                }
17098            }
17099        }
17100
17101        if (systemApp) {
17102            if (onExternal) {
17103                // Abort update; system app can't be replaced with app on sdcard
17104                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17105                        "Cannot install updates to system apps on sdcard");
17106                return;
17107            } else if (instantApp) {
17108                // Abort update; system app can't be replaced with an instant app
17109                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17110                        "Cannot update a system app with an instant app");
17111                return;
17112            }
17113        }
17114
17115        if (args.move != null) {
17116            // We did an in-place move, so dex is ready to roll
17117            scanFlags |= SCAN_NO_DEX;
17118            scanFlags |= SCAN_MOVE;
17119
17120            synchronized (mPackages) {
17121                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17122                if (ps == null) {
17123                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17124                            "Missing settings for moved package " + pkgName);
17125                }
17126
17127                // We moved the entire application as-is, so bring over the
17128                // previously derived ABI information.
17129                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17130                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17131            }
17132
17133        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17134            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17135            scanFlags |= SCAN_NO_DEX;
17136
17137            try {
17138                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17139                    args.abiOverride : pkg.cpuAbiOverride);
17140                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17141                        true /*extractLibs*/, mAppLib32InstallDir);
17142            } catch (PackageManagerException pme) {
17143                Slog.e(TAG, "Error deriving application ABI", pme);
17144                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17145                return;
17146            }
17147
17148            // Shared libraries for the package need to be updated.
17149            synchronized (mPackages) {
17150                try {
17151                    updateSharedLibrariesLPr(pkg, null);
17152                } catch (PackageManagerException e) {
17153                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17154                }
17155            }
17156
17157            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17158            // Do not run PackageDexOptimizer through the local performDexOpt
17159            // method because `pkg` may not be in `mPackages` yet.
17160            //
17161            // Also, don't fail application installs if the dexopt step fails.
17162            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17163                    null /* instructionSets */, false /* checkProfiles */,
17164                    getCompilerFilterForReason(REASON_INSTALL),
17165                    getOrCreateCompilerPackageStats(pkg),
17166                    mDexManager.isUsedByOtherApps(pkg.packageName));
17167            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17168
17169            // Notify BackgroundDexOptService that the package has been changed.
17170            // If this is an update of a package which used to fail to compile,
17171            // BDOS will remove it from its blacklist.
17172            // TODO: Layering violation
17173            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17174        }
17175
17176        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17177            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17178            return;
17179        }
17180
17181        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17182
17183        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17184                "installPackageLI")) {
17185            if (replace) {
17186                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17187                    // Static libs have a synthetic package name containing the version
17188                    // and cannot be updated as an update would get a new package name,
17189                    // unless this is the exact same version code which is useful for
17190                    // development.
17191                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17192                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17193                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17194                                + "static-shared libs cannot be updated");
17195                        return;
17196                    }
17197                }
17198                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17199                        installerPackageName, res, args.installReason);
17200            } else {
17201                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17202                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17203            }
17204        }
17205
17206        synchronized (mPackages) {
17207            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17208            if (ps != null) {
17209                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17210                ps.setUpdateAvailable(false /*updateAvailable*/);
17211            }
17212
17213            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17214            for (int i = 0; i < childCount; i++) {
17215                PackageParser.Package childPkg = pkg.childPackages.get(i);
17216                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17217                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17218                if (childPs != null) {
17219                    childRes.newUsers = childPs.queryInstalledUsers(
17220                            sUserManager.getUserIds(), true);
17221                }
17222            }
17223
17224            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17225                updateSequenceNumberLP(pkgName, res.newUsers);
17226                updateInstantAppInstallerLocked(pkgName);
17227            }
17228        }
17229    }
17230
17231    private void startIntentFilterVerifications(int userId, boolean replacing,
17232            PackageParser.Package pkg) {
17233        if (mIntentFilterVerifierComponent == null) {
17234            Slog.w(TAG, "No IntentFilter verification will not be done as "
17235                    + "there is no IntentFilterVerifier available!");
17236            return;
17237        }
17238
17239        final int verifierUid = getPackageUid(
17240                mIntentFilterVerifierComponent.getPackageName(),
17241                MATCH_DEBUG_TRIAGED_MISSING,
17242                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17243
17244        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17245        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17246        mHandler.sendMessage(msg);
17247
17248        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17249        for (int i = 0; i < childCount; i++) {
17250            PackageParser.Package childPkg = pkg.childPackages.get(i);
17251            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17252            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17253            mHandler.sendMessage(msg);
17254        }
17255    }
17256
17257    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17258            PackageParser.Package pkg) {
17259        int size = pkg.activities.size();
17260        if (size == 0) {
17261            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17262                    "No activity, so no need to verify any IntentFilter!");
17263            return;
17264        }
17265
17266        final boolean hasDomainURLs = hasDomainURLs(pkg);
17267        if (!hasDomainURLs) {
17268            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17269                    "No domain URLs, so no need to verify any IntentFilter!");
17270            return;
17271        }
17272
17273        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17274                + " if any IntentFilter from the " + size
17275                + " Activities needs verification ...");
17276
17277        int count = 0;
17278        final String packageName = pkg.packageName;
17279
17280        synchronized (mPackages) {
17281            // If this is a new install and we see that we've already run verification for this
17282            // package, we have nothing to do: it means the state was restored from backup.
17283            if (!replacing) {
17284                IntentFilterVerificationInfo ivi =
17285                        mSettings.getIntentFilterVerificationLPr(packageName);
17286                if (ivi != null) {
17287                    if (DEBUG_DOMAIN_VERIFICATION) {
17288                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17289                                + ivi.getStatusString());
17290                    }
17291                    return;
17292                }
17293            }
17294
17295            // If any filters need to be verified, then all need to be.
17296            boolean needToVerify = false;
17297            for (PackageParser.Activity a : pkg.activities) {
17298                for (ActivityIntentInfo filter : a.intents) {
17299                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17300                        if (DEBUG_DOMAIN_VERIFICATION) {
17301                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17302                        }
17303                        needToVerify = true;
17304                        break;
17305                    }
17306                }
17307            }
17308
17309            if (needToVerify) {
17310                final int verificationId = mIntentFilterVerificationToken++;
17311                for (PackageParser.Activity a : pkg.activities) {
17312                    for (ActivityIntentInfo filter : a.intents) {
17313                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17314                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17315                                    "Verification needed for IntentFilter:" + filter.toString());
17316                            mIntentFilterVerifier.addOneIntentFilterVerification(
17317                                    verifierUid, userId, verificationId, filter, packageName);
17318                            count++;
17319                        }
17320                    }
17321                }
17322            }
17323        }
17324
17325        if (count > 0) {
17326            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17327                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17328                    +  " for userId:" + userId);
17329            mIntentFilterVerifier.startVerifications(userId);
17330        } else {
17331            if (DEBUG_DOMAIN_VERIFICATION) {
17332                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17333            }
17334        }
17335    }
17336
17337    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17338        final ComponentName cn  = filter.activity.getComponentName();
17339        final String packageName = cn.getPackageName();
17340
17341        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17342                packageName);
17343        if (ivi == null) {
17344            return true;
17345        }
17346        int status = ivi.getStatus();
17347        switch (status) {
17348            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17349            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17350                return true;
17351
17352            default:
17353                // Nothing to do
17354                return false;
17355        }
17356    }
17357
17358    private static boolean isMultiArch(ApplicationInfo info) {
17359        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17360    }
17361
17362    private static boolean isExternal(PackageParser.Package pkg) {
17363        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17364    }
17365
17366    private static boolean isExternal(PackageSetting ps) {
17367        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17368    }
17369
17370    private static boolean isSystemApp(PackageParser.Package pkg) {
17371        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17372    }
17373
17374    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17375        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17376    }
17377
17378    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17379        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17380    }
17381
17382    private static boolean isSystemApp(PackageSetting ps) {
17383        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17384    }
17385
17386    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17387        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17388    }
17389
17390    private int packageFlagsToInstallFlags(PackageSetting ps) {
17391        int installFlags = 0;
17392        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17393            // This existing package was an external ASEC install when we have
17394            // the external flag without a UUID
17395            installFlags |= PackageManager.INSTALL_EXTERNAL;
17396        }
17397        if (ps.isForwardLocked()) {
17398            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17399        }
17400        return installFlags;
17401    }
17402
17403    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17404        if (isExternal(pkg)) {
17405            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17406                return StorageManager.UUID_PRIMARY_PHYSICAL;
17407            } else {
17408                return pkg.volumeUuid;
17409            }
17410        } else {
17411            return StorageManager.UUID_PRIVATE_INTERNAL;
17412        }
17413    }
17414
17415    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17416        if (isExternal(pkg)) {
17417            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17418                return mSettings.getExternalVersion();
17419            } else {
17420                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17421            }
17422        } else {
17423            return mSettings.getInternalVersion();
17424        }
17425    }
17426
17427    private void deleteTempPackageFiles() {
17428        final FilenameFilter filter = new FilenameFilter() {
17429            public boolean accept(File dir, String name) {
17430                return name.startsWith("vmdl") && name.endsWith(".tmp");
17431            }
17432        };
17433        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17434            file.delete();
17435        }
17436    }
17437
17438    @Override
17439    public void deletePackageAsUser(String packageName, int versionCode,
17440            IPackageDeleteObserver observer, int userId, int flags) {
17441        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17442                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17443    }
17444
17445    @Override
17446    public void deletePackageVersioned(VersionedPackage versionedPackage,
17447            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17448        mContext.enforceCallingOrSelfPermission(
17449                android.Manifest.permission.DELETE_PACKAGES, null);
17450        Preconditions.checkNotNull(versionedPackage);
17451        Preconditions.checkNotNull(observer);
17452        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17453                PackageManager.VERSION_CODE_HIGHEST,
17454                Integer.MAX_VALUE, "versionCode must be >= -1");
17455
17456        final String packageName = versionedPackage.getPackageName();
17457        // TODO: We will change version code to long, so in the new API it is long
17458        final int versionCode = (int) versionedPackage.getVersionCode();
17459        final String internalPackageName;
17460        synchronized (mPackages) {
17461            // Normalize package name to handle renamed packages and static libs
17462            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17463                    // TODO: We will change version code to long, so in the new API it is long
17464                    (int) versionedPackage.getVersionCode());
17465        }
17466
17467        final int uid = Binder.getCallingUid();
17468        if (!isOrphaned(internalPackageName)
17469                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17470            try {
17471                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17472                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17473                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17474                observer.onUserActionRequired(intent);
17475            } catch (RemoteException re) {
17476            }
17477            return;
17478        }
17479        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17480        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17481        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17482            mContext.enforceCallingOrSelfPermission(
17483                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17484                    "deletePackage for user " + userId);
17485        }
17486
17487        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17488            try {
17489                observer.onPackageDeleted(packageName,
17490                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17491            } catch (RemoteException re) {
17492            }
17493            return;
17494        }
17495
17496        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17497            try {
17498                observer.onPackageDeleted(packageName,
17499                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17500            } catch (RemoteException re) {
17501            }
17502            return;
17503        }
17504
17505        if (DEBUG_REMOVE) {
17506            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17507                    + " deleteAllUsers: " + deleteAllUsers + " version="
17508                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17509                    ? "VERSION_CODE_HIGHEST" : versionCode));
17510        }
17511        // Queue up an async operation since the package deletion may take a little while.
17512        mHandler.post(new Runnable() {
17513            public void run() {
17514                mHandler.removeCallbacks(this);
17515                int returnCode;
17516                if (!deleteAllUsers) {
17517                    returnCode = deletePackageX(internalPackageName, versionCode,
17518                            userId, deleteFlags);
17519                } else {
17520                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17521                            internalPackageName, users);
17522                    // If nobody is blocking uninstall, proceed with delete for all users
17523                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17524                        returnCode = deletePackageX(internalPackageName, versionCode,
17525                                userId, deleteFlags);
17526                    } else {
17527                        // Otherwise uninstall individually for users with blockUninstalls=false
17528                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17529                        for (int userId : users) {
17530                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17531                                returnCode = deletePackageX(internalPackageName, versionCode,
17532                                        userId, userFlags);
17533                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17534                                    Slog.w(TAG, "Package delete failed for user " + userId
17535                                            + ", returnCode " + returnCode);
17536                                }
17537                            }
17538                        }
17539                        // The app has only been marked uninstalled for certain users.
17540                        // We still need to report that delete was blocked
17541                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17542                    }
17543                }
17544                try {
17545                    observer.onPackageDeleted(packageName, returnCode, null);
17546                } catch (RemoteException e) {
17547                    Log.i(TAG, "Observer no longer exists.");
17548                } //end catch
17549            } //end run
17550        });
17551    }
17552
17553    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17554        if (pkg.staticSharedLibName != null) {
17555            return pkg.manifestPackageName;
17556        }
17557        return pkg.packageName;
17558    }
17559
17560    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17561        // Handle renamed packages
17562        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17563        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17564
17565        // Is this a static library?
17566        SparseArray<SharedLibraryEntry> versionedLib =
17567                mStaticLibsByDeclaringPackage.get(packageName);
17568        if (versionedLib == null || versionedLib.size() <= 0) {
17569            return packageName;
17570        }
17571
17572        // Figure out which lib versions the caller can see
17573        SparseIntArray versionsCallerCanSee = null;
17574        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17575        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17576                && callingAppId != Process.ROOT_UID) {
17577            versionsCallerCanSee = new SparseIntArray();
17578            String libName = versionedLib.valueAt(0).info.getName();
17579            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17580            if (uidPackages != null) {
17581                for (String uidPackage : uidPackages) {
17582                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17583                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17584                    if (libIdx >= 0) {
17585                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17586                        versionsCallerCanSee.append(libVersion, libVersion);
17587                    }
17588                }
17589            }
17590        }
17591
17592        // Caller can see nothing - done
17593        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17594            return packageName;
17595        }
17596
17597        // Find the version the caller can see and the app version code
17598        SharedLibraryEntry highestVersion = null;
17599        final int versionCount = versionedLib.size();
17600        for (int i = 0; i < versionCount; i++) {
17601            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17602            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17603                    // TODO: Remove cast for lib version once internally we support longs.
17604                    (int) libEntry.info.getVersion()) < 0) {
17605                continue;
17606            }
17607            // TODO: We will change version code to long, so in the new API it is long
17608            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17609            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17610                if (libVersionCode == versionCode) {
17611                    return libEntry.apk;
17612                }
17613            } else if (highestVersion == null) {
17614                highestVersion = libEntry;
17615            } else if (libVersionCode  > highestVersion.info
17616                    .getDeclaringPackage().getVersionCode()) {
17617                highestVersion = libEntry;
17618            }
17619        }
17620
17621        if (highestVersion != null) {
17622            return highestVersion.apk;
17623        }
17624
17625        return packageName;
17626    }
17627
17628    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17629        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17630              || callingUid == Process.SYSTEM_UID) {
17631            return true;
17632        }
17633        final int callingUserId = UserHandle.getUserId(callingUid);
17634        // If the caller installed the pkgName, then allow it to silently uninstall.
17635        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17636            return true;
17637        }
17638
17639        // Allow package verifier to silently uninstall.
17640        if (mRequiredVerifierPackage != null &&
17641                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17642            return true;
17643        }
17644
17645        // Allow package uninstaller to silently uninstall.
17646        if (mRequiredUninstallerPackage != null &&
17647                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17648            return true;
17649        }
17650
17651        // Allow storage manager to silently uninstall.
17652        if (mStorageManagerPackage != null &&
17653                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17654            return true;
17655        }
17656        return false;
17657    }
17658
17659    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17660        int[] result = EMPTY_INT_ARRAY;
17661        for (int userId : userIds) {
17662            if (getBlockUninstallForUser(packageName, userId)) {
17663                result = ArrayUtils.appendInt(result, userId);
17664            }
17665        }
17666        return result;
17667    }
17668
17669    @Override
17670    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17671        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17672    }
17673
17674    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17675        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17676                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17677        try {
17678            if (dpm != null) {
17679                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17680                        /* callingUserOnly =*/ false);
17681                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17682                        : deviceOwnerComponentName.getPackageName();
17683                // Does the package contains the device owner?
17684                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17685                // this check is probably not needed, since DO should be registered as a device
17686                // admin on some user too. (Original bug for this: b/17657954)
17687                if (packageName.equals(deviceOwnerPackageName)) {
17688                    return true;
17689                }
17690                // Does it contain a device admin for any user?
17691                int[] users;
17692                if (userId == UserHandle.USER_ALL) {
17693                    users = sUserManager.getUserIds();
17694                } else {
17695                    users = new int[]{userId};
17696                }
17697                for (int i = 0; i < users.length; ++i) {
17698                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17699                        return true;
17700                    }
17701                }
17702            }
17703        } catch (RemoteException e) {
17704        }
17705        return false;
17706    }
17707
17708    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17709        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17710    }
17711
17712    /**
17713     *  This method is an internal method that could be get invoked either
17714     *  to delete an installed package or to clean up a failed installation.
17715     *  After deleting an installed package, a broadcast is sent to notify any
17716     *  listeners that the package has been removed. For cleaning up a failed
17717     *  installation, the broadcast is not necessary since the package's
17718     *  installation wouldn't have sent the initial broadcast either
17719     *  The key steps in deleting a package are
17720     *  deleting the package information in internal structures like mPackages,
17721     *  deleting the packages base directories through installd
17722     *  updating mSettings to reflect current status
17723     *  persisting settings for later use
17724     *  sending a broadcast if necessary
17725     */
17726    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17727        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17728        final boolean res;
17729
17730        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17731                ? UserHandle.USER_ALL : userId;
17732
17733        if (isPackageDeviceAdmin(packageName, removeUser)) {
17734            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17735            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17736        }
17737
17738        PackageSetting uninstalledPs = null;
17739        PackageParser.Package pkg = null;
17740
17741        // for the uninstall-updates case and restricted profiles, remember the per-
17742        // user handle installed state
17743        int[] allUsers;
17744        synchronized (mPackages) {
17745            uninstalledPs = mSettings.mPackages.get(packageName);
17746            if (uninstalledPs == null) {
17747                Slog.w(TAG, "Not removing non-existent package " + packageName);
17748                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17749            }
17750
17751            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17752                    && uninstalledPs.versionCode != versionCode) {
17753                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17754                        + uninstalledPs.versionCode + " != " + versionCode);
17755                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17756            }
17757
17758            // Static shared libs can be declared by any package, so let us not
17759            // allow removing a package if it provides a lib others depend on.
17760            pkg = mPackages.get(packageName);
17761            if (pkg != null && pkg.staticSharedLibName != null) {
17762                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17763                        pkg.staticSharedLibVersion);
17764                if (libEntry != null) {
17765                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17766                            libEntry.info, 0, userId);
17767                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17768                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17769                                + " hosting lib " + libEntry.info.getName() + " version "
17770                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17771                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17772                    }
17773                }
17774            }
17775
17776            allUsers = sUserManager.getUserIds();
17777            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17778        }
17779
17780        final int freezeUser;
17781        if (isUpdatedSystemApp(uninstalledPs)
17782                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17783            // We're downgrading a system app, which will apply to all users, so
17784            // freeze them all during the downgrade
17785            freezeUser = UserHandle.USER_ALL;
17786        } else {
17787            freezeUser = removeUser;
17788        }
17789
17790        synchronized (mInstallLock) {
17791            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17792            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17793                    deleteFlags, "deletePackageX")) {
17794                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17795                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17796            }
17797            synchronized (mPackages) {
17798                if (res) {
17799                    if (pkg != null) {
17800                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17801                    }
17802                    updateSequenceNumberLP(packageName, info.removedUsers);
17803                    updateInstantAppInstallerLocked(packageName);
17804                }
17805            }
17806        }
17807
17808        if (res) {
17809            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17810            info.sendPackageRemovedBroadcasts(killApp);
17811            info.sendSystemPackageUpdatedBroadcasts();
17812            info.sendSystemPackageAppearedBroadcasts();
17813        }
17814        // Force a gc here.
17815        Runtime.getRuntime().gc();
17816        // Delete the resources here after sending the broadcast to let
17817        // other processes clean up before deleting resources.
17818        if (info.args != null) {
17819            synchronized (mInstallLock) {
17820                info.args.doPostDeleteLI(true);
17821            }
17822        }
17823
17824        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17825    }
17826
17827    static class PackageRemovedInfo {
17828        final PackageSender packageSender;
17829        String removedPackage;
17830        int uid = -1;
17831        int removedAppId = -1;
17832        int[] origUsers;
17833        int[] removedUsers = null;
17834        int[] broadcastUsers = null;
17835        SparseArray<Integer> installReasons;
17836        boolean isRemovedPackageSystemUpdate = false;
17837        boolean isUpdate;
17838        boolean dataRemoved;
17839        boolean removedForAllUsers;
17840        boolean isStaticSharedLib;
17841        // Clean up resources deleted packages.
17842        InstallArgs args = null;
17843        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17844        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17845
17846        PackageRemovedInfo(PackageSender packageSender) {
17847            this.packageSender = packageSender;
17848        }
17849
17850        void sendPackageRemovedBroadcasts(boolean killApp) {
17851            sendPackageRemovedBroadcastInternal(killApp);
17852            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17853            for (int i = 0; i < childCount; i++) {
17854                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17855                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17856            }
17857        }
17858
17859        void sendSystemPackageUpdatedBroadcasts() {
17860            if (isRemovedPackageSystemUpdate) {
17861                sendSystemPackageUpdatedBroadcastsInternal();
17862                final int childCount = (removedChildPackages != null)
17863                        ? removedChildPackages.size() : 0;
17864                for (int i = 0; i < childCount; i++) {
17865                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17866                    if (childInfo.isRemovedPackageSystemUpdate) {
17867                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17868                    }
17869                }
17870            }
17871        }
17872
17873        void sendSystemPackageAppearedBroadcasts() {
17874            final int packageCount = (appearedChildPackages != null)
17875                    ? appearedChildPackages.size() : 0;
17876            for (int i = 0; i < packageCount; i++) {
17877                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17878                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17879                    true, UserHandle.getAppId(installedInfo.uid),
17880                    installedInfo.newUsers);
17881            }
17882        }
17883
17884        private void sendSystemPackageUpdatedBroadcastsInternal() {
17885            Bundle extras = new Bundle(2);
17886            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17887            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17888            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17889                removedPackage, extras, 0, null, null, null);
17890            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17891                removedPackage, extras, 0, null, null, null);
17892            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17893                null, null, 0, removedPackage, null, null);
17894        }
17895
17896        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17897            // Don't send static shared library removal broadcasts as these
17898            // libs are visible only the the apps that depend on them an one
17899            // cannot remove the library if it has a dependency.
17900            if (isStaticSharedLib) {
17901                return;
17902            }
17903            Bundle extras = new Bundle(2);
17904            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17905            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17906            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17907            if (isUpdate || isRemovedPackageSystemUpdate) {
17908                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17909            }
17910            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17911            if (removedPackage != null) {
17912                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17913                    removedPackage, extras, 0, null, null, broadcastUsers);
17914                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17915                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17916                        removedPackage, extras,
17917                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17918                        null, null, broadcastUsers);
17919                }
17920            }
17921            if (removedAppId >= 0) {
17922                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
17923                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
17924            }
17925        }
17926
17927        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17928            removedUsers = userIds;
17929            if (removedUsers == null) {
17930                broadcastUsers = null;
17931                return;
17932            }
17933
17934            broadcastUsers = EMPTY_INT_ARRAY;
17935            for (int i = userIds.length - 1; i >= 0; --i) {
17936                final int userId = userIds[i];
17937                if (deletedPackageSetting.getInstantApp(userId)) {
17938                    continue;
17939                }
17940                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17941            }
17942        }
17943    }
17944
17945    /*
17946     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17947     * flag is not set, the data directory is removed as well.
17948     * make sure this flag is set for partially installed apps. If not its meaningless to
17949     * delete a partially installed application.
17950     */
17951    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17952            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17953        String packageName = ps.name;
17954        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17955        // Retrieve object to delete permissions for shared user later on
17956        final PackageParser.Package deletedPkg;
17957        final PackageSetting deletedPs;
17958        // reader
17959        synchronized (mPackages) {
17960            deletedPkg = mPackages.get(packageName);
17961            deletedPs = mSettings.mPackages.get(packageName);
17962            if (outInfo != null) {
17963                outInfo.removedPackage = packageName;
17964                outInfo.isStaticSharedLib = deletedPkg != null
17965                        && deletedPkg.staticSharedLibName != null;
17966                outInfo.populateUsers(deletedPs == null ? null
17967                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17968            }
17969        }
17970
17971        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17972
17973        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17974            final PackageParser.Package resolvedPkg;
17975            if (deletedPkg != null) {
17976                resolvedPkg = deletedPkg;
17977            } else {
17978                // We don't have a parsed package when it lives on an ejected
17979                // adopted storage device, so fake something together
17980                resolvedPkg = new PackageParser.Package(ps.name);
17981                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17982            }
17983            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17984                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17985            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17986            if (outInfo != null) {
17987                outInfo.dataRemoved = true;
17988            }
17989            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17990        }
17991
17992        int removedAppId = -1;
17993
17994        // writer
17995        synchronized (mPackages) {
17996            boolean installedStateChanged = false;
17997            if (deletedPs != null) {
17998                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17999                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18000                    clearDefaultBrowserIfNeeded(packageName);
18001                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18002                    removedAppId = mSettings.removePackageLPw(packageName);
18003                    if (outInfo != null) {
18004                        outInfo.removedAppId = removedAppId;
18005                    }
18006                    updatePermissionsLPw(deletedPs.name, null, 0);
18007                    if (deletedPs.sharedUser != null) {
18008                        // Remove permissions associated with package. Since runtime
18009                        // permissions are per user we have to kill the removed package
18010                        // or packages running under the shared user of the removed
18011                        // package if revoking the permissions requested only by the removed
18012                        // package is successful and this causes a change in gids.
18013                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18014                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18015                                    userId);
18016                            if (userIdToKill == UserHandle.USER_ALL
18017                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18018                                // If gids changed for this user, kill all affected packages.
18019                                mHandler.post(new Runnable() {
18020                                    @Override
18021                                    public void run() {
18022                                        // This has to happen with no lock held.
18023                                        killApplication(deletedPs.name, deletedPs.appId,
18024                                                KILL_APP_REASON_GIDS_CHANGED);
18025                                    }
18026                                });
18027                                break;
18028                            }
18029                        }
18030                    }
18031                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18032                }
18033                // make sure to preserve per-user disabled state if this removal was just
18034                // a downgrade of a system app to the factory package
18035                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18036                    if (DEBUG_REMOVE) {
18037                        Slog.d(TAG, "Propagating install state across downgrade");
18038                    }
18039                    for (int userId : allUserHandles) {
18040                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18041                        if (DEBUG_REMOVE) {
18042                            Slog.d(TAG, "    user " + userId + " => " + installed);
18043                        }
18044                        if (installed != ps.getInstalled(userId)) {
18045                            installedStateChanged = true;
18046                        }
18047                        ps.setInstalled(installed, userId);
18048                    }
18049                }
18050            }
18051            // can downgrade to reader
18052            if (writeSettings) {
18053                // Save settings now
18054                mSettings.writeLPr();
18055            }
18056            if (installedStateChanged) {
18057                mSettings.writeKernelMappingLPr(ps);
18058            }
18059        }
18060        if (removedAppId != -1) {
18061            // A user ID was deleted here. Go through all users and remove it
18062            // from KeyStore.
18063            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18064        }
18065    }
18066
18067    static boolean locationIsPrivileged(File path) {
18068        try {
18069            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18070                    .getCanonicalPath();
18071            return path.getCanonicalPath().startsWith(privilegedAppDir);
18072        } catch (IOException e) {
18073            Slog.e(TAG, "Unable to access code path " + path);
18074        }
18075        return false;
18076    }
18077
18078    /*
18079     * Tries to delete system package.
18080     */
18081    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18082            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18083            boolean writeSettings) {
18084        if (deletedPs.parentPackageName != null) {
18085            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18086            return false;
18087        }
18088
18089        final boolean applyUserRestrictions
18090                = (allUserHandles != null) && (outInfo.origUsers != null);
18091        final PackageSetting disabledPs;
18092        // Confirm if the system package has been updated
18093        // An updated system app can be deleted. This will also have to restore
18094        // the system pkg from system partition
18095        // reader
18096        synchronized (mPackages) {
18097            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18098        }
18099
18100        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18101                + " disabledPs=" + disabledPs);
18102
18103        if (disabledPs == null) {
18104            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18105            return false;
18106        } else if (DEBUG_REMOVE) {
18107            Slog.d(TAG, "Deleting system pkg from data partition");
18108        }
18109
18110        if (DEBUG_REMOVE) {
18111            if (applyUserRestrictions) {
18112                Slog.d(TAG, "Remembering install states:");
18113                for (int userId : allUserHandles) {
18114                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18115                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18116                }
18117            }
18118        }
18119
18120        // Delete the updated package
18121        outInfo.isRemovedPackageSystemUpdate = true;
18122        if (outInfo.removedChildPackages != null) {
18123            final int childCount = (deletedPs.childPackageNames != null)
18124                    ? deletedPs.childPackageNames.size() : 0;
18125            for (int i = 0; i < childCount; i++) {
18126                String childPackageName = deletedPs.childPackageNames.get(i);
18127                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18128                        .contains(childPackageName)) {
18129                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18130                            childPackageName);
18131                    if (childInfo != null) {
18132                        childInfo.isRemovedPackageSystemUpdate = true;
18133                    }
18134                }
18135            }
18136        }
18137
18138        if (disabledPs.versionCode < deletedPs.versionCode) {
18139            // Delete data for downgrades
18140            flags &= ~PackageManager.DELETE_KEEP_DATA;
18141        } else {
18142            // Preserve data by setting flag
18143            flags |= PackageManager.DELETE_KEEP_DATA;
18144        }
18145
18146        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18147                outInfo, writeSettings, disabledPs.pkg);
18148        if (!ret) {
18149            return false;
18150        }
18151
18152        // writer
18153        synchronized (mPackages) {
18154            // Reinstate the old system package
18155            enableSystemPackageLPw(disabledPs.pkg);
18156            // Remove any native libraries from the upgraded package.
18157            removeNativeBinariesLI(deletedPs);
18158        }
18159
18160        // Install the system package
18161        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18162        int parseFlags = mDefParseFlags
18163                | PackageParser.PARSE_MUST_BE_APK
18164                | PackageParser.PARSE_IS_SYSTEM
18165                | PackageParser.PARSE_IS_SYSTEM_DIR;
18166        if (locationIsPrivileged(disabledPs.codePath)) {
18167            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18168        }
18169
18170        final PackageParser.Package newPkg;
18171        try {
18172            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18173                0 /* currentTime */, null);
18174        } catch (PackageManagerException e) {
18175            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18176                    + e.getMessage());
18177            return false;
18178        }
18179
18180        try {
18181            // update shared libraries for the newly re-installed system package
18182            updateSharedLibrariesLPr(newPkg, null);
18183        } catch (PackageManagerException e) {
18184            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18185        }
18186
18187        prepareAppDataAfterInstallLIF(newPkg);
18188
18189        // writer
18190        synchronized (mPackages) {
18191            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18192
18193            // Propagate the permissions state as we do not want to drop on the floor
18194            // runtime permissions. The update permissions method below will take
18195            // care of removing obsolete permissions and grant install permissions.
18196            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18197            updatePermissionsLPw(newPkg.packageName, newPkg,
18198                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18199
18200            if (applyUserRestrictions) {
18201                boolean installedStateChanged = false;
18202                if (DEBUG_REMOVE) {
18203                    Slog.d(TAG, "Propagating install state across reinstall");
18204                }
18205                for (int userId : allUserHandles) {
18206                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18207                    if (DEBUG_REMOVE) {
18208                        Slog.d(TAG, "    user " + userId + " => " + installed);
18209                    }
18210                    if (installed != ps.getInstalled(userId)) {
18211                        installedStateChanged = true;
18212                    }
18213                    ps.setInstalled(installed, userId);
18214
18215                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18216                }
18217                // Regardless of writeSettings we need to ensure that this restriction
18218                // state propagation is persisted
18219                mSettings.writeAllUsersPackageRestrictionsLPr();
18220                if (installedStateChanged) {
18221                    mSettings.writeKernelMappingLPr(ps);
18222                }
18223            }
18224            // can downgrade to reader here
18225            if (writeSettings) {
18226                mSettings.writeLPr();
18227            }
18228        }
18229        return true;
18230    }
18231
18232    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18233            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18234            PackageRemovedInfo outInfo, boolean writeSettings,
18235            PackageParser.Package replacingPackage) {
18236        synchronized (mPackages) {
18237            if (outInfo != null) {
18238                outInfo.uid = ps.appId;
18239            }
18240
18241            if (outInfo != null && outInfo.removedChildPackages != null) {
18242                final int childCount = (ps.childPackageNames != null)
18243                        ? ps.childPackageNames.size() : 0;
18244                for (int i = 0; i < childCount; i++) {
18245                    String childPackageName = ps.childPackageNames.get(i);
18246                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18247                    if (childPs == null) {
18248                        return false;
18249                    }
18250                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18251                            childPackageName);
18252                    if (childInfo != null) {
18253                        childInfo.uid = childPs.appId;
18254                    }
18255                }
18256            }
18257        }
18258
18259        // Delete package data from internal structures and also remove data if flag is set
18260        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18261
18262        // Delete the child packages data
18263        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18264        for (int i = 0; i < childCount; i++) {
18265            PackageSetting childPs;
18266            synchronized (mPackages) {
18267                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18268            }
18269            if (childPs != null) {
18270                PackageRemovedInfo childOutInfo = (outInfo != null
18271                        && outInfo.removedChildPackages != null)
18272                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18273                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18274                        && (replacingPackage != null
18275                        && !replacingPackage.hasChildPackage(childPs.name))
18276                        ? flags & ~DELETE_KEEP_DATA : flags;
18277                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18278                        deleteFlags, writeSettings);
18279            }
18280        }
18281
18282        // Delete application code and resources only for parent packages
18283        if (ps.parentPackageName == null) {
18284            if (deleteCodeAndResources && (outInfo != null)) {
18285                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18286                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18287                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18288            }
18289        }
18290
18291        return true;
18292    }
18293
18294    @Override
18295    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18296            int userId) {
18297        mContext.enforceCallingOrSelfPermission(
18298                android.Manifest.permission.DELETE_PACKAGES, null);
18299        synchronized (mPackages) {
18300            PackageSetting ps = mSettings.mPackages.get(packageName);
18301            if (ps == null) {
18302                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18303                return false;
18304            }
18305            // Cannot block uninstall of static shared libs as they are
18306            // considered a part of the using app (emulating static linking).
18307            // Also static libs are installed always on internal storage.
18308            PackageParser.Package pkg = mPackages.get(packageName);
18309            if (pkg != null && pkg.staticSharedLibName != null) {
18310                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18311                        + " providing static shared library: " + pkg.staticSharedLibName);
18312                return false;
18313            }
18314            if (!ps.getInstalled(userId)) {
18315                // Can't block uninstall for an app that is not installed or enabled.
18316                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18317                return false;
18318            }
18319            ps.setBlockUninstall(blockUninstall, userId);
18320            mSettings.writePackageRestrictionsLPr(userId);
18321        }
18322        return true;
18323    }
18324
18325    @Override
18326    public boolean getBlockUninstallForUser(String packageName, int userId) {
18327        synchronized (mPackages) {
18328            PackageSetting ps = mSettings.mPackages.get(packageName);
18329            if (ps == null) {
18330                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18331                return false;
18332            }
18333            return ps.getBlockUninstall(userId);
18334        }
18335    }
18336
18337    @Override
18338    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18339        int callingUid = Binder.getCallingUid();
18340        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18341            throw new SecurityException(
18342                    "setRequiredForSystemUser can only be run by the system or root");
18343        }
18344        synchronized (mPackages) {
18345            PackageSetting ps = mSettings.mPackages.get(packageName);
18346            if (ps == null) {
18347                Log.w(TAG, "Package doesn't exist: " + packageName);
18348                return false;
18349            }
18350            if (systemUserApp) {
18351                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18352            } else {
18353                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18354            }
18355            mSettings.writeLPr();
18356        }
18357        return true;
18358    }
18359
18360    /*
18361     * This method handles package deletion in general
18362     */
18363    private boolean deletePackageLIF(String packageName, UserHandle user,
18364            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18365            PackageRemovedInfo outInfo, boolean writeSettings,
18366            PackageParser.Package replacingPackage) {
18367        if (packageName == null) {
18368            Slog.w(TAG, "Attempt to delete null packageName.");
18369            return false;
18370        }
18371
18372        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18373
18374        PackageSetting ps;
18375        synchronized (mPackages) {
18376            ps = mSettings.mPackages.get(packageName);
18377            if (ps == null) {
18378                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18379                return false;
18380            }
18381
18382            if (ps.parentPackageName != null && (!isSystemApp(ps)
18383                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18384                if (DEBUG_REMOVE) {
18385                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18386                            + ((user == null) ? UserHandle.USER_ALL : user));
18387                }
18388                final int removedUserId = (user != null) ? user.getIdentifier()
18389                        : UserHandle.USER_ALL;
18390                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18391                    return false;
18392                }
18393                markPackageUninstalledForUserLPw(ps, user);
18394                scheduleWritePackageRestrictionsLocked(user);
18395                return true;
18396            }
18397        }
18398
18399        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18400                && user.getIdentifier() != UserHandle.USER_ALL)) {
18401            // The caller is asking that the package only be deleted for a single
18402            // user.  To do this, we just mark its uninstalled state and delete
18403            // its data. If this is a system app, we only allow this to happen if
18404            // they have set the special DELETE_SYSTEM_APP which requests different
18405            // semantics than normal for uninstalling system apps.
18406            markPackageUninstalledForUserLPw(ps, user);
18407
18408            if (!isSystemApp(ps)) {
18409                // Do not uninstall the APK if an app should be cached
18410                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18411                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18412                    // Other user still have this package installed, so all
18413                    // we need to do is clear this user's data and save that
18414                    // it is uninstalled.
18415                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18416                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18417                        return false;
18418                    }
18419                    scheduleWritePackageRestrictionsLocked(user);
18420                    return true;
18421                } else {
18422                    // We need to set it back to 'installed' so the uninstall
18423                    // broadcasts will be sent correctly.
18424                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18425                    ps.setInstalled(true, user.getIdentifier());
18426                    mSettings.writeKernelMappingLPr(ps);
18427                }
18428            } else {
18429                // This is a system app, so we assume that the
18430                // other users still have this package installed, so all
18431                // we need to do is clear this user's data and save that
18432                // it is uninstalled.
18433                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18434                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18435                    return false;
18436                }
18437                scheduleWritePackageRestrictionsLocked(user);
18438                return true;
18439            }
18440        }
18441
18442        // If we are deleting a composite package for all users, keep track
18443        // of result for each child.
18444        if (ps.childPackageNames != null && outInfo != null) {
18445            synchronized (mPackages) {
18446                final int childCount = ps.childPackageNames.size();
18447                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18448                for (int i = 0; i < childCount; i++) {
18449                    String childPackageName = ps.childPackageNames.get(i);
18450                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18451                    childInfo.removedPackage = childPackageName;
18452                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18453                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18454                    if (childPs != null) {
18455                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18456                    }
18457                }
18458            }
18459        }
18460
18461        boolean ret = false;
18462        if (isSystemApp(ps)) {
18463            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18464            // When an updated system application is deleted we delete the existing resources
18465            // as well and fall back to existing code in system partition
18466            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18467        } else {
18468            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18469            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18470                    outInfo, writeSettings, replacingPackage);
18471        }
18472
18473        // Take a note whether we deleted the package for all users
18474        if (outInfo != null) {
18475            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18476            if (outInfo.removedChildPackages != null) {
18477                synchronized (mPackages) {
18478                    final int childCount = outInfo.removedChildPackages.size();
18479                    for (int i = 0; i < childCount; i++) {
18480                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18481                        if (childInfo != null) {
18482                            childInfo.removedForAllUsers = mPackages.get(
18483                                    childInfo.removedPackage) == null;
18484                        }
18485                    }
18486                }
18487            }
18488            // If we uninstalled an update to a system app there may be some
18489            // child packages that appeared as they are declared in the system
18490            // app but were not declared in the update.
18491            if (isSystemApp(ps)) {
18492                synchronized (mPackages) {
18493                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18494                    final int childCount = (updatedPs.childPackageNames != null)
18495                            ? updatedPs.childPackageNames.size() : 0;
18496                    for (int i = 0; i < childCount; i++) {
18497                        String childPackageName = updatedPs.childPackageNames.get(i);
18498                        if (outInfo.removedChildPackages == null
18499                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18500                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18501                            if (childPs == null) {
18502                                continue;
18503                            }
18504                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18505                            installRes.name = childPackageName;
18506                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18507                            installRes.pkg = mPackages.get(childPackageName);
18508                            installRes.uid = childPs.pkg.applicationInfo.uid;
18509                            if (outInfo.appearedChildPackages == null) {
18510                                outInfo.appearedChildPackages = new ArrayMap<>();
18511                            }
18512                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18513                        }
18514                    }
18515                }
18516            }
18517        }
18518
18519        return ret;
18520    }
18521
18522    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18523        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18524                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18525        for (int nextUserId : userIds) {
18526            if (DEBUG_REMOVE) {
18527                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18528            }
18529            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18530                    false /*installed*/,
18531                    true /*stopped*/,
18532                    true /*notLaunched*/,
18533                    false /*hidden*/,
18534                    false /*suspended*/,
18535                    false /*instantApp*/,
18536                    null /*lastDisableAppCaller*/,
18537                    null /*enabledComponents*/,
18538                    null /*disabledComponents*/,
18539                    false /*blockUninstall*/,
18540                    ps.readUserState(nextUserId).domainVerificationStatus,
18541                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18542        }
18543        mSettings.writeKernelMappingLPr(ps);
18544    }
18545
18546    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18547            PackageRemovedInfo outInfo) {
18548        final PackageParser.Package pkg;
18549        synchronized (mPackages) {
18550            pkg = mPackages.get(ps.name);
18551        }
18552
18553        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18554                : new int[] {userId};
18555        for (int nextUserId : userIds) {
18556            if (DEBUG_REMOVE) {
18557                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18558                        + nextUserId);
18559            }
18560
18561            destroyAppDataLIF(pkg, userId,
18562                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18563            destroyAppProfilesLIF(pkg, userId);
18564            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18565            schedulePackageCleaning(ps.name, nextUserId, false);
18566            synchronized (mPackages) {
18567                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18568                    scheduleWritePackageRestrictionsLocked(nextUserId);
18569                }
18570                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18571            }
18572        }
18573
18574        if (outInfo != null) {
18575            outInfo.removedPackage = ps.name;
18576            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18577            outInfo.removedAppId = ps.appId;
18578            outInfo.removedUsers = userIds;
18579            outInfo.broadcastUsers = userIds;
18580        }
18581
18582        return true;
18583    }
18584
18585    private final class ClearStorageConnection implements ServiceConnection {
18586        IMediaContainerService mContainerService;
18587
18588        @Override
18589        public void onServiceConnected(ComponentName name, IBinder service) {
18590            synchronized (this) {
18591                mContainerService = IMediaContainerService.Stub
18592                        .asInterface(Binder.allowBlocking(service));
18593                notifyAll();
18594            }
18595        }
18596
18597        @Override
18598        public void onServiceDisconnected(ComponentName name) {
18599        }
18600    }
18601
18602    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18603        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18604
18605        final boolean mounted;
18606        if (Environment.isExternalStorageEmulated()) {
18607            mounted = true;
18608        } else {
18609            final String status = Environment.getExternalStorageState();
18610
18611            mounted = status.equals(Environment.MEDIA_MOUNTED)
18612                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18613        }
18614
18615        if (!mounted) {
18616            return;
18617        }
18618
18619        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18620        int[] users;
18621        if (userId == UserHandle.USER_ALL) {
18622            users = sUserManager.getUserIds();
18623        } else {
18624            users = new int[] { userId };
18625        }
18626        final ClearStorageConnection conn = new ClearStorageConnection();
18627        if (mContext.bindServiceAsUser(
18628                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18629            try {
18630                for (int curUser : users) {
18631                    long timeout = SystemClock.uptimeMillis() + 5000;
18632                    synchronized (conn) {
18633                        long now;
18634                        while (conn.mContainerService == null &&
18635                                (now = SystemClock.uptimeMillis()) < timeout) {
18636                            try {
18637                                conn.wait(timeout - now);
18638                            } catch (InterruptedException e) {
18639                            }
18640                        }
18641                    }
18642                    if (conn.mContainerService == null) {
18643                        return;
18644                    }
18645
18646                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18647                    clearDirectory(conn.mContainerService,
18648                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18649                    if (allData) {
18650                        clearDirectory(conn.mContainerService,
18651                                userEnv.buildExternalStorageAppDataDirs(packageName));
18652                        clearDirectory(conn.mContainerService,
18653                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18654                    }
18655                }
18656            } finally {
18657                mContext.unbindService(conn);
18658            }
18659        }
18660    }
18661
18662    @Override
18663    public void clearApplicationProfileData(String packageName) {
18664        enforceSystemOrRoot("Only the system can clear all profile data");
18665
18666        final PackageParser.Package pkg;
18667        synchronized (mPackages) {
18668            pkg = mPackages.get(packageName);
18669        }
18670
18671        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18672            synchronized (mInstallLock) {
18673                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18674            }
18675        }
18676    }
18677
18678    @Override
18679    public void clearApplicationUserData(final String packageName,
18680            final IPackageDataObserver observer, final int userId) {
18681        mContext.enforceCallingOrSelfPermission(
18682                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18683
18684        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18685                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18686
18687        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18688            throw new SecurityException("Cannot clear data for a protected package: "
18689                    + packageName);
18690        }
18691        // Queue up an async operation since the package deletion may take a little while.
18692        mHandler.post(new Runnable() {
18693            public void run() {
18694                mHandler.removeCallbacks(this);
18695                final boolean succeeded;
18696                try (PackageFreezer freezer = freezePackage(packageName,
18697                        "clearApplicationUserData")) {
18698                    synchronized (mInstallLock) {
18699                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18700                    }
18701                    clearExternalStorageDataSync(packageName, userId, true);
18702                    synchronized (mPackages) {
18703                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18704                                packageName, userId);
18705                    }
18706                }
18707                if (succeeded) {
18708                    // invoke DeviceStorageMonitor's update method to clear any notifications
18709                    DeviceStorageMonitorInternal dsm = LocalServices
18710                            .getService(DeviceStorageMonitorInternal.class);
18711                    if (dsm != null) {
18712                        dsm.checkMemory();
18713                    }
18714                }
18715                if(observer != null) {
18716                    try {
18717                        observer.onRemoveCompleted(packageName, succeeded);
18718                    } catch (RemoteException e) {
18719                        Log.i(TAG, "Observer no longer exists.");
18720                    }
18721                } //end if observer
18722            } //end run
18723        });
18724    }
18725
18726    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18727        if (packageName == null) {
18728            Slog.w(TAG, "Attempt to delete null packageName.");
18729            return false;
18730        }
18731
18732        // Try finding details about the requested package
18733        PackageParser.Package pkg;
18734        synchronized (mPackages) {
18735            pkg = mPackages.get(packageName);
18736            if (pkg == null) {
18737                final PackageSetting ps = mSettings.mPackages.get(packageName);
18738                if (ps != null) {
18739                    pkg = ps.pkg;
18740                }
18741            }
18742
18743            if (pkg == null) {
18744                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18745                return false;
18746            }
18747
18748            PackageSetting ps = (PackageSetting) pkg.mExtras;
18749            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18750        }
18751
18752        clearAppDataLIF(pkg, userId,
18753                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18754
18755        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18756        removeKeystoreDataIfNeeded(userId, appId);
18757
18758        UserManagerInternal umInternal = getUserManagerInternal();
18759        final int flags;
18760        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18761            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18762        } else if (umInternal.isUserRunning(userId)) {
18763            flags = StorageManager.FLAG_STORAGE_DE;
18764        } else {
18765            flags = 0;
18766        }
18767        prepareAppDataContentsLIF(pkg, userId, flags);
18768
18769        return true;
18770    }
18771
18772    /**
18773     * Reverts user permission state changes (permissions and flags) in
18774     * all packages for a given user.
18775     *
18776     * @param userId The device user for which to do a reset.
18777     */
18778    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18779        final int packageCount = mPackages.size();
18780        for (int i = 0; i < packageCount; i++) {
18781            PackageParser.Package pkg = mPackages.valueAt(i);
18782            PackageSetting ps = (PackageSetting) pkg.mExtras;
18783            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18784        }
18785    }
18786
18787    private void resetNetworkPolicies(int userId) {
18788        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18789    }
18790
18791    /**
18792     * Reverts user permission state changes (permissions and flags).
18793     *
18794     * @param ps The package for which to reset.
18795     * @param userId The device user for which to do a reset.
18796     */
18797    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18798            final PackageSetting ps, final int userId) {
18799        if (ps.pkg == null) {
18800            return;
18801        }
18802
18803        // These are flags that can change base on user actions.
18804        final int userSettableMask = FLAG_PERMISSION_USER_SET
18805                | FLAG_PERMISSION_USER_FIXED
18806                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18807                | FLAG_PERMISSION_REVIEW_REQUIRED;
18808
18809        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18810                | FLAG_PERMISSION_POLICY_FIXED;
18811
18812        boolean writeInstallPermissions = false;
18813        boolean writeRuntimePermissions = false;
18814
18815        final int permissionCount = ps.pkg.requestedPermissions.size();
18816        for (int i = 0; i < permissionCount; i++) {
18817            String permission = ps.pkg.requestedPermissions.get(i);
18818
18819            BasePermission bp = mSettings.mPermissions.get(permission);
18820            if (bp == null) {
18821                continue;
18822            }
18823
18824            // If shared user we just reset the state to which only this app contributed.
18825            if (ps.sharedUser != null) {
18826                boolean used = false;
18827                final int packageCount = ps.sharedUser.packages.size();
18828                for (int j = 0; j < packageCount; j++) {
18829                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18830                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18831                            && pkg.pkg.requestedPermissions.contains(permission)) {
18832                        used = true;
18833                        break;
18834                    }
18835                }
18836                if (used) {
18837                    continue;
18838                }
18839            }
18840
18841            PermissionsState permissionsState = ps.getPermissionsState();
18842
18843            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18844
18845            // Always clear the user settable flags.
18846            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18847                    bp.name) != null;
18848            // If permission review is enabled and this is a legacy app, mark the
18849            // permission as requiring a review as this is the initial state.
18850            int flags = 0;
18851            if (mPermissionReviewRequired
18852                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18853                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18854            }
18855            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18856                if (hasInstallState) {
18857                    writeInstallPermissions = true;
18858                } else {
18859                    writeRuntimePermissions = true;
18860                }
18861            }
18862
18863            // Below is only runtime permission handling.
18864            if (!bp.isRuntime()) {
18865                continue;
18866            }
18867
18868            // Never clobber system or policy.
18869            if ((oldFlags & policyOrSystemFlags) != 0) {
18870                continue;
18871            }
18872
18873            // If this permission was granted by default, make sure it is.
18874            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18875                if (permissionsState.grantRuntimePermission(bp, userId)
18876                        != PERMISSION_OPERATION_FAILURE) {
18877                    writeRuntimePermissions = true;
18878                }
18879            // If permission review is enabled the permissions for a legacy apps
18880            // are represented as constantly granted runtime ones, so don't revoke.
18881            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18882                // Otherwise, reset the permission.
18883                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18884                switch (revokeResult) {
18885                    case PERMISSION_OPERATION_SUCCESS:
18886                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18887                        writeRuntimePermissions = true;
18888                        final int appId = ps.appId;
18889                        mHandler.post(new Runnable() {
18890                            @Override
18891                            public void run() {
18892                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18893                            }
18894                        });
18895                    } break;
18896                }
18897            }
18898        }
18899
18900        // Synchronously write as we are taking permissions away.
18901        if (writeRuntimePermissions) {
18902            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18903        }
18904
18905        // Synchronously write as we are taking permissions away.
18906        if (writeInstallPermissions) {
18907            mSettings.writeLPr();
18908        }
18909    }
18910
18911    /**
18912     * Remove entries from the keystore daemon. Will only remove it if the
18913     * {@code appId} is valid.
18914     */
18915    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18916        if (appId < 0) {
18917            return;
18918        }
18919
18920        final KeyStore keyStore = KeyStore.getInstance();
18921        if (keyStore != null) {
18922            if (userId == UserHandle.USER_ALL) {
18923                for (final int individual : sUserManager.getUserIds()) {
18924                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18925                }
18926            } else {
18927                keyStore.clearUid(UserHandle.getUid(userId, appId));
18928            }
18929        } else {
18930            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18931        }
18932    }
18933
18934    @Override
18935    public void deleteApplicationCacheFiles(final String packageName,
18936            final IPackageDataObserver observer) {
18937        final int userId = UserHandle.getCallingUserId();
18938        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18939    }
18940
18941    @Override
18942    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18943            final IPackageDataObserver observer) {
18944        mContext.enforceCallingOrSelfPermission(
18945                android.Manifest.permission.DELETE_CACHE_FILES, null);
18946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18947                /* requireFullPermission= */ true, /* checkShell= */ false,
18948                "delete application cache files");
18949
18950        final PackageParser.Package pkg;
18951        synchronized (mPackages) {
18952            pkg = mPackages.get(packageName);
18953        }
18954
18955        // Queue up an async operation since the package deletion may take a little while.
18956        mHandler.post(new Runnable() {
18957            public void run() {
18958                synchronized (mInstallLock) {
18959                    final int flags = StorageManager.FLAG_STORAGE_DE
18960                            | StorageManager.FLAG_STORAGE_CE;
18961                    // We're only clearing cache files, so we don't care if the
18962                    // app is unfrozen and still able to run
18963                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18964                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18965                }
18966                clearExternalStorageDataSync(packageName, userId, false);
18967                if (observer != null) {
18968                    try {
18969                        observer.onRemoveCompleted(packageName, true);
18970                    } catch (RemoteException e) {
18971                        Log.i(TAG, "Observer no longer exists.");
18972                    }
18973                }
18974            }
18975        });
18976    }
18977
18978    @Override
18979    public void getPackageSizeInfo(final String packageName, int userHandle,
18980            final IPackageStatsObserver observer) {
18981        throw new UnsupportedOperationException(
18982                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18983    }
18984
18985    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18986        final PackageSetting ps;
18987        synchronized (mPackages) {
18988            ps = mSettings.mPackages.get(packageName);
18989            if (ps == null) {
18990                Slog.w(TAG, "Failed to find settings for " + packageName);
18991                return false;
18992            }
18993        }
18994
18995        final String[] packageNames = { packageName };
18996        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18997        final String[] codePaths = { ps.codePathString };
18998
18999        try {
19000            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19001                    ps.appId, ceDataInodes, codePaths, stats);
19002
19003            // For now, ignore code size of packages on system partition
19004            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19005                stats.codeSize = 0;
19006            }
19007
19008            // External clients expect these to be tracked separately
19009            stats.dataSize -= stats.cacheSize;
19010
19011        } catch (InstallerException e) {
19012            Slog.w(TAG, String.valueOf(e));
19013            return false;
19014        }
19015
19016        return true;
19017    }
19018
19019    private int getUidTargetSdkVersionLockedLPr(int uid) {
19020        Object obj = mSettings.getUserIdLPr(uid);
19021        if (obj instanceof SharedUserSetting) {
19022            final SharedUserSetting sus = (SharedUserSetting) obj;
19023            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19024            final Iterator<PackageSetting> it = sus.packages.iterator();
19025            while (it.hasNext()) {
19026                final PackageSetting ps = it.next();
19027                if (ps.pkg != null) {
19028                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19029                    if (v < vers) vers = v;
19030                }
19031            }
19032            return vers;
19033        } else if (obj instanceof PackageSetting) {
19034            final PackageSetting ps = (PackageSetting) obj;
19035            if (ps.pkg != null) {
19036                return ps.pkg.applicationInfo.targetSdkVersion;
19037            }
19038        }
19039        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19040    }
19041
19042    @Override
19043    public void addPreferredActivity(IntentFilter filter, int match,
19044            ComponentName[] set, ComponentName activity, int userId) {
19045        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19046                "Adding preferred");
19047    }
19048
19049    private void addPreferredActivityInternal(IntentFilter filter, int match,
19050            ComponentName[] set, ComponentName activity, boolean always, int userId,
19051            String opname) {
19052        // writer
19053        int callingUid = Binder.getCallingUid();
19054        enforceCrossUserPermission(callingUid, userId,
19055                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19056        if (filter.countActions() == 0) {
19057            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19058            return;
19059        }
19060        synchronized (mPackages) {
19061            if (mContext.checkCallingOrSelfPermission(
19062                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19063                    != PackageManager.PERMISSION_GRANTED) {
19064                if (getUidTargetSdkVersionLockedLPr(callingUid)
19065                        < Build.VERSION_CODES.FROYO) {
19066                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19067                            + callingUid);
19068                    return;
19069                }
19070                mContext.enforceCallingOrSelfPermission(
19071                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19072            }
19073
19074            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19075            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19076                    + userId + ":");
19077            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19078            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19079            scheduleWritePackageRestrictionsLocked(userId);
19080            postPreferredActivityChangedBroadcast(userId);
19081        }
19082    }
19083
19084    private void postPreferredActivityChangedBroadcast(int userId) {
19085        mHandler.post(() -> {
19086            final IActivityManager am = ActivityManager.getService();
19087            if (am == null) {
19088                return;
19089            }
19090
19091            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19092            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19093            try {
19094                am.broadcastIntent(null, intent, null, null,
19095                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19096                        null, false, false, userId);
19097            } catch (RemoteException e) {
19098            }
19099        });
19100    }
19101
19102    @Override
19103    public void replacePreferredActivity(IntentFilter filter, int match,
19104            ComponentName[] set, ComponentName activity, int userId) {
19105        if (filter.countActions() != 1) {
19106            throw new IllegalArgumentException(
19107                    "replacePreferredActivity expects filter to have only 1 action.");
19108        }
19109        if (filter.countDataAuthorities() != 0
19110                || filter.countDataPaths() != 0
19111                || filter.countDataSchemes() > 1
19112                || filter.countDataTypes() != 0) {
19113            throw new IllegalArgumentException(
19114                    "replacePreferredActivity expects filter to have no data authorities, " +
19115                    "paths, or types; and at most one scheme.");
19116        }
19117
19118        final int callingUid = Binder.getCallingUid();
19119        enforceCrossUserPermission(callingUid, userId,
19120                true /* requireFullPermission */, false /* checkShell */,
19121                "replace preferred activity");
19122        synchronized (mPackages) {
19123            if (mContext.checkCallingOrSelfPermission(
19124                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19125                    != PackageManager.PERMISSION_GRANTED) {
19126                if (getUidTargetSdkVersionLockedLPr(callingUid)
19127                        < Build.VERSION_CODES.FROYO) {
19128                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19129                            + Binder.getCallingUid());
19130                    return;
19131                }
19132                mContext.enforceCallingOrSelfPermission(
19133                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19134            }
19135
19136            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19137            if (pir != null) {
19138                // Get all of the existing entries that exactly match this filter.
19139                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19140                if (existing != null && existing.size() == 1) {
19141                    PreferredActivity cur = existing.get(0);
19142                    if (DEBUG_PREFERRED) {
19143                        Slog.i(TAG, "Checking replace of preferred:");
19144                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19145                        if (!cur.mPref.mAlways) {
19146                            Slog.i(TAG, "  -- CUR; not mAlways!");
19147                        } else {
19148                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19149                            Slog.i(TAG, "  -- CUR: mSet="
19150                                    + Arrays.toString(cur.mPref.mSetComponents));
19151                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19152                            Slog.i(TAG, "  -- NEW: mMatch="
19153                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19154                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19155                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19156                        }
19157                    }
19158                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19159                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19160                            && cur.mPref.sameSet(set)) {
19161                        // Setting the preferred activity to what it happens to be already
19162                        if (DEBUG_PREFERRED) {
19163                            Slog.i(TAG, "Replacing with same preferred activity "
19164                                    + cur.mPref.mShortComponent + " for user "
19165                                    + userId + ":");
19166                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19167                        }
19168                        return;
19169                    }
19170                }
19171
19172                if (existing != null) {
19173                    if (DEBUG_PREFERRED) {
19174                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19175                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19176                    }
19177                    for (int i = 0; i < existing.size(); i++) {
19178                        PreferredActivity pa = existing.get(i);
19179                        if (DEBUG_PREFERRED) {
19180                            Slog.i(TAG, "Removing existing preferred activity "
19181                                    + pa.mPref.mComponent + ":");
19182                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19183                        }
19184                        pir.removeFilter(pa);
19185                    }
19186                }
19187            }
19188            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19189                    "Replacing preferred");
19190        }
19191    }
19192
19193    @Override
19194    public void clearPackagePreferredActivities(String packageName) {
19195        final int uid = Binder.getCallingUid();
19196        // writer
19197        synchronized (mPackages) {
19198            PackageParser.Package pkg = mPackages.get(packageName);
19199            if (pkg == null || pkg.applicationInfo.uid != uid) {
19200                if (mContext.checkCallingOrSelfPermission(
19201                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19202                        != PackageManager.PERMISSION_GRANTED) {
19203                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19204                            < Build.VERSION_CODES.FROYO) {
19205                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19206                                + Binder.getCallingUid());
19207                        return;
19208                    }
19209                    mContext.enforceCallingOrSelfPermission(
19210                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19211                }
19212            }
19213
19214            int user = UserHandle.getCallingUserId();
19215            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19216                scheduleWritePackageRestrictionsLocked(user);
19217            }
19218        }
19219    }
19220
19221    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19222    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19223        ArrayList<PreferredActivity> removed = null;
19224        boolean changed = false;
19225        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19226            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19227            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19228            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19229                continue;
19230            }
19231            Iterator<PreferredActivity> it = pir.filterIterator();
19232            while (it.hasNext()) {
19233                PreferredActivity pa = it.next();
19234                // Mark entry for removal only if it matches the package name
19235                // and the entry is of type "always".
19236                if (packageName == null ||
19237                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19238                                && pa.mPref.mAlways)) {
19239                    if (removed == null) {
19240                        removed = new ArrayList<PreferredActivity>();
19241                    }
19242                    removed.add(pa);
19243                }
19244            }
19245            if (removed != null) {
19246                for (int j=0; j<removed.size(); j++) {
19247                    PreferredActivity pa = removed.get(j);
19248                    pir.removeFilter(pa);
19249                }
19250                changed = true;
19251            }
19252        }
19253        if (changed) {
19254            postPreferredActivityChangedBroadcast(userId);
19255        }
19256        return changed;
19257    }
19258
19259    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19260    private void clearIntentFilterVerificationsLPw(int userId) {
19261        final int packageCount = mPackages.size();
19262        for (int i = 0; i < packageCount; i++) {
19263            PackageParser.Package pkg = mPackages.valueAt(i);
19264            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19265        }
19266    }
19267
19268    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19269    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19270        if (userId == UserHandle.USER_ALL) {
19271            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19272                    sUserManager.getUserIds())) {
19273                for (int oneUserId : sUserManager.getUserIds()) {
19274                    scheduleWritePackageRestrictionsLocked(oneUserId);
19275                }
19276            }
19277        } else {
19278            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19279                scheduleWritePackageRestrictionsLocked(userId);
19280            }
19281        }
19282    }
19283
19284    void clearDefaultBrowserIfNeeded(String packageName) {
19285        for (int oneUserId : sUserManager.getUserIds()) {
19286            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19287            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19288            if (packageName.equals(defaultBrowserPackageName)) {
19289                setDefaultBrowserPackageName(null, oneUserId);
19290            }
19291        }
19292    }
19293
19294    @Override
19295    public void resetApplicationPreferences(int userId) {
19296        mContext.enforceCallingOrSelfPermission(
19297                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19298        final long identity = Binder.clearCallingIdentity();
19299        // writer
19300        try {
19301            synchronized (mPackages) {
19302                clearPackagePreferredActivitiesLPw(null, userId);
19303                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19304                // TODO: We have to reset the default SMS and Phone. This requires
19305                // significant refactoring to keep all default apps in the package
19306                // manager (cleaner but more work) or have the services provide
19307                // callbacks to the package manager to request a default app reset.
19308                applyFactoryDefaultBrowserLPw(userId);
19309                clearIntentFilterVerificationsLPw(userId);
19310                primeDomainVerificationsLPw(userId);
19311                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19312                scheduleWritePackageRestrictionsLocked(userId);
19313            }
19314            resetNetworkPolicies(userId);
19315        } finally {
19316            Binder.restoreCallingIdentity(identity);
19317        }
19318    }
19319
19320    @Override
19321    public int getPreferredActivities(List<IntentFilter> outFilters,
19322            List<ComponentName> outActivities, String packageName) {
19323
19324        int num = 0;
19325        final int userId = UserHandle.getCallingUserId();
19326        // reader
19327        synchronized (mPackages) {
19328            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19329            if (pir != null) {
19330                final Iterator<PreferredActivity> it = pir.filterIterator();
19331                while (it.hasNext()) {
19332                    final PreferredActivity pa = it.next();
19333                    if (packageName == null
19334                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19335                                    && pa.mPref.mAlways)) {
19336                        if (outFilters != null) {
19337                            outFilters.add(new IntentFilter(pa));
19338                        }
19339                        if (outActivities != null) {
19340                            outActivities.add(pa.mPref.mComponent);
19341                        }
19342                    }
19343                }
19344            }
19345        }
19346
19347        return num;
19348    }
19349
19350    @Override
19351    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19352            int userId) {
19353        int callingUid = Binder.getCallingUid();
19354        if (callingUid != Process.SYSTEM_UID) {
19355            throw new SecurityException(
19356                    "addPersistentPreferredActivity can only be run by the system");
19357        }
19358        if (filter.countActions() == 0) {
19359            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19360            return;
19361        }
19362        synchronized (mPackages) {
19363            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19364                    ":");
19365            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19366            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19367                    new PersistentPreferredActivity(filter, activity));
19368            scheduleWritePackageRestrictionsLocked(userId);
19369            postPreferredActivityChangedBroadcast(userId);
19370        }
19371    }
19372
19373    @Override
19374    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19375        int callingUid = Binder.getCallingUid();
19376        if (callingUid != Process.SYSTEM_UID) {
19377            throw new SecurityException(
19378                    "clearPackagePersistentPreferredActivities can only be run by the system");
19379        }
19380        ArrayList<PersistentPreferredActivity> removed = null;
19381        boolean changed = false;
19382        synchronized (mPackages) {
19383            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19384                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19385                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19386                        .valueAt(i);
19387                if (userId != thisUserId) {
19388                    continue;
19389                }
19390                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19391                while (it.hasNext()) {
19392                    PersistentPreferredActivity ppa = it.next();
19393                    // Mark entry for removal only if it matches the package name.
19394                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19395                        if (removed == null) {
19396                            removed = new ArrayList<PersistentPreferredActivity>();
19397                        }
19398                        removed.add(ppa);
19399                    }
19400                }
19401                if (removed != null) {
19402                    for (int j=0; j<removed.size(); j++) {
19403                        PersistentPreferredActivity ppa = removed.get(j);
19404                        ppir.removeFilter(ppa);
19405                    }
19406                    changed = true;
19407                }
19408            }
19409
19410            if (changed) {
19411                scheduleWritePackageRestrictionsLocked(userId);
19412                postPreferredActivityChangedBroadcast(userId);
19413            }
19414        }
19415    }
19416
19417    /**
19418     * Common machinery for picking apart a restored XML blob and passing
19419     * it to a caller-supplied functor to be applied to the running system.
19420     */
19421    private void restoreFromXml(XmlPullParser parser, int userId,
19422            String expectedStartTag, BlobXmlRestorer functor)
19423            throws IOException, XmlPullParserException {
19424        int type;
19425        while ((type = parser.next()) != XmlPullParser.START_TAG
19426                && type != XmlPullParser.END_DOCUMENT) {
19427        }
19428        if (type != XmlPullParser.START_TAG) {
19429            // oops didn't find a start tag?!
19430            if (DEBUG_BACKUP) {
19431                Slog.e(TAG, "Didn't find start tag during restore");
19432            }
19433            return;
19434        }
19435Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19436        // this is supposed to be TAG_PREFERRED_BACKUP
19437        if (!expectedStartTag.equals(parser.getName())) {
19438            if (DEBUG_BACKUP) {
19439                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19440            }
19441            return;
19442        }
19443
19444        // skip interfering stuff, then we're aligned with the backing implementation
19445        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19446Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19447        functor.apply(parser, userId);
19448    }
19449
19450    private interface BlobXmlRestorer {
19451        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19452    }
19453
19454    /**
19455     * Non-Binder method, support for the backup/restore mechanism: write the
19456     * full set of preferred activities in its canonical XML format.  Returns the
19457     * XML output as a byte array, or null if there is none.
19458     */
19459    @Override
19460    public byte[] getPreferredActivityBackup(int userId) {
19461        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19462            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19463        }
19464
19465        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19466        try {
19467            final XmlSerializer serializer = new FastXmlSerializer();
19468            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19469            serializer.startDocument(null, true);
19470            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19471
19472            synchronized (mPackages) {
19473                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19474            }
19475
19476            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19477            serializer.endDocument();
19478            serializer.flush();
19479        } catch (Exception e) {
19480            if (DEBUG_BACKUP) {
19481                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19482            }
19483            return null;
19484        }
19485
19486        return dataStream.toByteArray();
19487    }
19488
19489    @Override
19490    public void restorePreferredActivities(byte[] backup, int userId) {
19491        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19492            throw new SecurityException("Only the system may call restorePreferredActivities()");
19493        }
19494
19495        try {
19496            final XmlPullParser parser = Xml.newPullParser();
19497            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19498            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19499                    new BlobXmlRestorer() {
19500                        @Override
19501                        public void apply(XmlPullParser parser, int userId)
19502                                throws XmlPullParserException, IOException {
19503                            synchronized (mPackages) {
19504                                mSettings.readPreferredActivitiesLPw(parser, userId);
19505                            }
19506                        }
19507                    } );
19508        } catch (Exception e) {
19509            if (DEBUG_BACKUP) {
19510                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19511            }
19512        }
19513    }
19514
19515    /**
19516     * Non-Binder method, support for the backup/restore mechanism: write the
19517     * default browser (etc) settings in its canonical XML format.  Returns the default
19518     * browser XML representation as a byte array, or null if there is none.
19519     */
19520    @Override
19521    public byte[] getDefaultAppsBackup(int userId) {
19522        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19523            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19524        }
19525
19526        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19527        try {
19528            final XmlSerializer serializer = new FastXmlSerializer();
19529            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19530            serializer.startDocument(null, true);
19531            serializer.startTag(null, TAG_DEFAULT_APPS);
19532
19533            synchronized (mPackages) {
19534                mSettings.writeDefaultAppsLPr(serializer, userId);
19535            }
19536
19537            serializer.endTag(null, TAG_DEFAULT_APPS);
19538            serializer.endDocument();
19539            serializer.flush();
19540        } catch (Exception e) {
19541            if (DEBUG_BACKUP) {
19542                Slog.e(TAG, "Unable to write default apps for backup", e);
19543            }
19544            return null;
19545        }
19546
19547        return dataStream.toByteArray();
19548    }
19549
19550    @Override
19551    public void restoreDefaultApps(byte[] backup, int userId) {
19552        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19553            throw new SecurityException("Only the system may call restoreDefaultApps()");
19554        }
19555
19556        try {
19557            final XmlPullParser parser = Xml.newPullParser();
19558            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19559            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19560                    new BlobXmlRestorer() {
19561                        @Override
19562                        public void apply(XmlPullParser parser, int userId)
19563                                throws XmlPullParserException, IOException {
19564                            synchronized (mPackages) {
19565                                mSettings.readDefaultAppsLPw(parser, userId);
19566                            }
19567                        }
19568                    } );
19569        } catch (Exception e) {
19570            if (DEBUG_BACKUP) {
19571                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19572            }
19573        }
19574    }
19575
19576    @Override
19577    public byte[] getIntentFilterVerificationBackup(int userId) {
19578        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19579            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19580        }
19581
19582        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19583        try {
19584            final XmlSerializer serializer = new FastXmlSerializer();
19585            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19586            serializer.startDocument(null, true);
19587            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19588
19589            synchronized (mPackages) {
19590                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19591            }
19592
19593            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19594            serializer.endDocument();
19595            serializer.flush();
19596        } catch (Exception e) {
19597            if (DEBUG_BACKUP) {
19598                Slog.e(TAG, "Unable to write default apps for backup", e);
19599            }
19600            return null;
19601        }
19602
19603        return dataStream.toByteArray();
19604    }
19605
19606    @Override
19607    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19608        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19609            throw new SecurityException("Only the system may call restorePreferredActivities()");
19610        }
19611
19612        try {
19613            final XmlPullParser parser = Xml.newPullParser();
19614            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19615            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19616                    new BlobXmlRestorer() {
19617                        @Override
19618                        public void apply(XmlPullParser parser, int userId)
19619                                throws XmlPullParserException, IOException {
19620                            synchronized (mPackages) {
19621                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19622                                mSettings.writeLPr();
19623                            }
19624                        }
19625                    } );
19626        } catch (Exception e) {
19627            if (DEBUG_BACKUP) {
19628                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19629            }
19630        }
19631    }
19632
19633    @Override
19634    public byte[] getPermissionGrantBackup(int userId) {
19635        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19636            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19637        }
19638
19639        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19640        try {
19641            final XmlSerializer serializer = new FastXmlSerializer();
19642            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19643            serializer.startDocument(null, true);
19644            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19645
19646            synchronized (mPackages) {
19647                serializeRuntimePermissionGrantsLPr(serializer, userId);
19648            }
19649
19650            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19651            serializer.endDocument();
19652            serializer.flush();
19653        } catch (Exception e) {
19654            if (DEBUG_BACKUP) {
19655                Slog.e(TAG, "Unable to write default apps for backup", e);
19656            }
19657            return null;
19658        }
19659
19660        return dataStream.toByteArray();
19661    }
19662
19663    @Override
19664    public void restorePermissionGrants(byte[] backup, int userId) {
19665        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19666            throw new SecurityException("Only the system may call restorePermissionGrants()");
19667        }
19668
19669        try {
19670            final XmlPullParser parser = Xml.newPullParser();
19671            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19672            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19673                    new BlobXmlRestorer() {
19674                        @Override
19675                        public void apply(XmlPullParser parser, int userId)
19676                                throws XmlPullParserException, IOException {
19677                            synchronized (mPackages) {
19678                                processRestoredPermissionGrantsLPr(parser, userId);
19679                            }
19680                        }
19681                    } );
19682        } catch (Exception e) {
19683            if (DEBUG_BACKUP) {
19684                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19685            }
19686        }
19687    }
19688
19689    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19690            throws IOException {
19691        serializer.startTag(null, TAG_ALL_GRANTS);
19692
19693        final int N = mSettings.mPackages.size();
19694        for (int i = 0; i < N; i++) {
19695            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19696            boolean pkgGrantsKnown = false;
19697
19698            PermissionsState packagePerms = ps.getPermissionsState();
19699
19700            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19701                final int grantFlags = state.getFlags();
19702                // only look at grants that are not system/policy fixed
19703                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19704                    final boolean isGranted = state.isGranted();
19705                    // And only back up the user-twiddled state bits
19706                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19707                        final String packageName = mSettings.mPackages.keyAt(i);
19708                        if (!pkgGrantsKnown) {
19709                            serializer.startTag(null, TAG_GRANT);
19710                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19711                            pkgGrantsKnown = true;
19712                        }
19713
19714                        final boolean userSet =
19715                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19716                        final boolean userFixed =
19717                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19718                        final boolean revoke =
19719                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19720
19721                        serializer.startTag(null, TAG_PERMISSION);
19722                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19723                        if (isGranted) {
19724                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19725                        }
19726                        if (userSet) {
19727                            serializer.attribute(null, ATTR_USER_SET, "true");
19728                        }
19729                        if (userFixed) {
19730                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19731                        }
19732                        if (revoke) {
19733                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19734                        }
19735                        serializer.endTag(null, TAG_PERMISSION);
19736                    }
19737                }
19738            }
19739
19740            if (pkgGrantsKnown) {
19741                serializer.endTag(null, TAG_GRANT);
19742            }
19743        }
19744
19745        serializer.endTag(null, TAG_ALL_GRANTS);
19746    }
19747
19748    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19749            throws XmlPullParserException, IOException {
19750        String pkgName = null;
19751        int outerDepth = parser.getDepth();
19752        int type;
19753        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19754                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19755            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19756                continue;
19757            }
19758
19759            final String tagName = parser.getName();
19760            if (tagName.equals(TAG_GRANT)) {
19761                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19762                if (DEBUG_BACKUP) {
19763                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19764                }
19765            } else if (tagName.equals(TAG_PERMISSION)) {
19766
19767                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19768                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19769
19770                int newFlagSet = 0;
19771                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19772                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19773                }
19774                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19775                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19776                }
19777                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19778                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19779                }
19780                if (DEBUG_BACKUP) {
19781                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19782                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19783                }
19784                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19785                if (ps != null) {
19786                    // Already installed so we apply the grant immediately
19787                    if (DEBUG_BACKUP) {
19788                        Slog.v(TAG, "        + already installed; applying");
19789                    }
19790                    PermissionsState perms = ps.getPermissionsState();
19791                    BasePermission bp = mSettings.mPermissions.get(permName);
19792                    if (bp != null) {
19793                        if (isGranted) {
19794                            perms.grantRuntimePermission(bp, userId);
19795                        }
19796                        if (newFlagSet != 0) {
19797                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19798                        }
19799                    }
19800                } else {
19801                    // Need to wait for post-restore install to apply the grant
19802                    if (DEBUG_BACKUP) {
19803                        Slog.v(TAG, "        - not yet installed; saving for later");
19804                    }
19805                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19806                            isGranted, newFlagSet, userId);
19807                }
19808            } else {
19809                PackageManagerService.reportSettingsProblem(Log.WARN,
19810                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19811                XmlUtils.skipCurrentTag(parser);
19812            }
19813        }
19814
19815        scheduleWriteSettingsLocked();
19816        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19817    }
19818
19819    @Override
19820    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19821            int sourceUserId, int targetUserId, int flags) {
19822        mContext.enforceCallingOrSelfPermission(
19823                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19824        int callingUid = Binder.getCallingUid();
19825        enforceOwnerRights(ownerPackage, callingUid);
19826        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19827        if (intentFilter.countActions() == 0) {
19828            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19829            return;
19830        }
19831        synchronized (mPackages) {
19832            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19833                    ownerPackage, targetUserId, flags);
19834            CrossProfileIntentResolver resolver =
19835                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19836            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19837            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19838            if (existing != null) {
19839                int size = existing.size();
19840                for (int i = 0; i < size; i++) {
19841                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19842                        return;
19843                    }
19844                }
19845            }
19846            resolver.addFilter(newFilter);
19847            scheduleWritePackageRestrictionsLocked(sourceUserId);
19848        }
19849    }
19850
19851    @Override
19852    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19853        mContext.enforceCallingOrSelfPermission(
19854                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19855        int callingUid = Binder.getCallingUid();
19856        enforceOwnerRights(ownerPackage, callingUid);
19857        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19858        synchronized (mPackages) {
19859            CrossProfileIntentResolver resolver =
19860                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19861            ArraySet<CrossProfileIntentFilter> set =
19862                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19863            for (CrossProfileIntentFilter filter : set) {
19864                if (filter.getOwnerPackage().equals(ownerPackage)) {
19865                    resolver.removeFilter(filter);
19866                }
19867            }
19868            scheduleWritePackageRestrictionsLocked(sourceUserId);
19869        }
19870    }
19871
19872    // Enforcing that callingUid is owning pkg on userId
19873    private void enforceOwnerRights(String pkg, int callingUid) {
19874        // The system owns everything.
19875        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19876            return;
19877        }
19878        int callingUserId = UserHandle.getUserId(callingUid);
19879        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19880        if (pi == null) {
19881            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19882                    + callingUserId);
19883        }
19884        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19885            throw new SecurityException("Calling uid " + callingUid
19886                    + " does not own package " + pkg);
19887        }
19888    }
19889
19890    @Override
19891    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19892        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19893    }
19894
19895    /**
19896     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19897     * then reports the most likely home activity or null if there are more than one.
19898     */
19899    public ComponentName getDefaultHomeActivity(int userId) {
19900        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19901        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19902        if (cn != null) {
19903            return cn;
19904        }
19905
19906        // Find the launcher with the highest priority and return that component if there are no
19907        // other home activity with the same priority.
19908        int lastPriority = Integer.MIN_VALUE;
19909        ComponentName lastComponent = null;
19910        final int size = allHomeCandidates.size();
19911        for (int i = 0; i < size; i++) {
19912            final ResolveInfo ri = allHomeCandidates.get(i);
19913            if (ri.priority > lastPriority) {
19914                lastComponent = ri.activityInfo.getComponentName();
19915                lastPriority = ri.priority;
19916            } else if (ri.priority == lastPriority) {
19917                // Two components found with same priority.
19918                lastComponent = null;
19919            }
19920        }
19921        return lastComponent;
19922    }
19923
19924    private Intent getHomeIntent() {
19925        Intent intent = new Intent(Intent.ACTION_MAIN);
19926        intent.addCategory(Intent.CATEGORY_HOME);
19927        intent.addCategory(Intent.CATEGORY_DEFAULT);
19928        return intent;
19929    }
19930
19931    private IntentFilter getHomeFilter() {
19932        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19933        filter.addCategory(Intent.CATEGORY_HOME);
19934        filter.addCategory(Intent.CATEGORY_DEFAULT);
19935        return filter;
19936    }
19937
19938    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19939            int userId) {
19940        Intent intent  = getHomeIntent();
19941        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19942                PackageManager.GET_META_DATA, userId);
19943        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19944                true, false, false, userId);
19945
19946        allHomeCandidates.clear();
19947        if (list != null) {
19948            for (ResolveInfo ri : list) {
19949                allHomeCandidates.add(ri);
19950            }
19951        }
19952        return (preferred == null || preferred.activityInfo == null)
19953                ? null
19954                : new ComponentName(preferred.activityInfo.packageName,
19955                        preferred.activityInfo.name);
19956    }
19957
19958    @Override
19959    public void setHomeActivity(ComponentName comp, int userId) {
19960        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19961        getHomeActivitiesAsUser(homeActivities, userId);
19962
19963        boolean found = false;
19964
19965        final int size = homeActivities.size();
19966        final ComponentName[] set = new ComponentName[size];
19967        for (int i = 0; i < size; i++) {
19968            final ResolveInfo candidate = homeActivities.get(i);
19969            final ActivityInfo info = candidate.activityInfo;
19970            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19971            set[i] = activityName;
19972            if (!found && activityName.equals(comp)) {
19973                found = true;
19974            }
19975        }
19976        if (!found) {
19977            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19978                    + userId);
19979        }
19980        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19981                set, comp, userId);
19982    }
19983
19984    private @Nullable String getSetupWizardPackageName() {
19985        final Intent intent = new Intent(Intent.ACTION_MAIN);
19986        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19987
19988        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19989                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19990                        | MATCH_DISABLED_COMPONENTS,
19991                UserHandle.myUserId());
19992        if (matches.size() == 1) {
19993            return matches.get(0).getComponentInfo().packageName;
19994        } else {
19995            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19996                    + ": matches=" + matches);
19997            return null;
19998        }
19999    }
20000
20001    private @Nullable String getStorageManagerPackageName() {
20002        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20003
20004        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20005                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20006                        | MATCH_DISABLED_COMPONENTS,
20007                UserHandle.myUserId());
20008        if (matches.size() == 1) {
20009            return matches.get(0).getComponentInfo().packageName;
20010        } else {
20011            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20012                    + matches.size() + ": matches=" + matches);
20013            return null;
20014        }
20015    }
20016
20017    @Override
20018    public void setApplicationEnabledSetting(String appPackageName,
20019            int newState, int flags, int userId, String callingPackage) {
20020        if (!sUserManager.exists(userId)) return;
20021        if (callingPackage == null) {
20022            callingPackage = Integer.toString(Binder.getCallingUid());
20023        }
20024        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20025    }
20026
20027    @Override
20028    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20029        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20030        synchronized (mPackages) {
20031            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20032            if (pkgSetting != null) {
20033                pkgSetting.setUpdateAvailable(updateAvailable);
20034            }
20035        }
20036    }
20037
20038    @Override
20039    public void setComponentEnabledSetting(ComponentName componentName,
20040            int newState, int flags, int userId) {
20041        if (!sUserManager.exists(userId)) return;
20042        setEnabledSetting(componentName.getPackageName(),
20043                componentName.getClassName(), newState, flags, userId, null);
20044    }
20045
20046    private void setEnabledSetting(final String packageName, String className, int newState,
20047            final int flags, int userId, String callingPackage) {
20048        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20049              || newState == COMPONENT_ENABLED_STATE_ENABLED
20050              || newState == COMPONENT_ENABLED_STATE_DISABLED
20051              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20052              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20053            throw new IllegalArgumentException("Invalid new component state: "
20054                    + newState);
20055        }
20056        PackageSetting pkgSetting;
20057        final int uid = Binder.getCallingUid();
20058        final int permission;
20059        if (uid == Process.SYSTEM_UID) {
20060            permission = PackageManager.PERMISSION_GRANTED;
20061        } else {
20062            permission = mContext.checkCallingOrSelfPermission(
20063                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20064        }
20065        enforceCrossUserPermission(uid, userId,
20066                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20067        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20068        boolean sendNow = false;
20069        boolean isApp = (className == null);
20070        String componentName = isApp ? packageName : className;
20071        int packageUid = -1;
20072        ArrayList<String> components;
20073
20074        // writer
20075        synchronized (mPackages) {
20076            pkgSetting = mSettings.mPackages.get(packageName);
20077            if (pkgSetting == null) {
20078                if (className == null) {
20079                    throw new IllegalArgumentException("Unknown package: " + packageName);
20080                }
20081                throw new IllegalArgumentException(
20082                        "Unknown component: " + packageName + "/" + className);
20083            }
20084        }
20085
20086        // Limit who can change which apps
20087        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20088            // Don't allow apps that don't have permission to modify other apps
20089            if (!allowedByPermission) {
20090                throw new SecurityException(
20091                        "Permission Denial: attempt to change component state from pid="
20092                        + Binder.getCallingPid()
20093                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20094            }
20095            // Don't allow changing protected packages.
20096            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20097                throw new SecurityException("Cannot disable a protected package: " + packageName);
20098            }
20099        }
20100
20101        synchronized (mPackages) {
20102            if (uid == Process.SHELL_UID
20103                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20104                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20105                // unless it is a test package.
20106                int oldState = pkgSetting.getEnabled(userId);
20107                if (className == null
20108                    &&
20109                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20110                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20111                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20112                    &&
20113                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20114                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20115                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20116                    // ok
20117                } else {
20118                    throw new SecurityException(
20119                            "Shell cannot change component state for " + packageName + "/"
20120                            + className + " to " + newState);
20121                }
20122            }
20123            if (className == null) {
20124                // We're dealing with an application/package level state change
20125                if (pkgSetting.getEnabled(userId) == newState) {
20126                    // Nothing to do
20127                    return;
20128                }
20129                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20130                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20131                    // Don't care about who enables an app.
20132                    callingPackage = null;
20133                }
20134                pkgSetting.setEnabled(newState, userId, callingPackage);
20135                // pkgSetting.pkg.mSetEnabled = newState;
20136            } else {
20137                // We're dealing with a component level state change
20138                // First, verify that this is a valid class name.
20139                PackageParser.Package pkg = pkgSetting.pkg;
20140                if (pkg == null || !pkg.hasComponentClassName(className)) {
20141                    if (pkg != null &&
20142                            pkg.applicationInfo.targetSdkVersion >=
20143                                    Build.VERSION_CODES.JELLY_BEAN) {
20144                        throw new IllegalArgumentException("Component class " + className
20145                                + " does not exist in " + packageName);
20146                    } else {
20147                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20148                                + className + " does not exist in " + packageName);
20149                    }
20150                }
20151                switch (newState) {
20152                case COMPONENT_ENABLED_STATE_ENABLED:
20153                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20154                        return;
20155                    }
20156                    break;
20157                case COMPONENT_ENABLED_STATE_DISABLED:
20158                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20159                        return;
20160                    }
20161                    break;
20162                case COMPONENT_ENABLED_STATE_DEFAULT:
20163                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20164                        return;
20165                    }
20166                    break;
20167                default:
20168                    Slog.e(TAG, "Invalid new component state: " + newState);
20169                    return;
20170                }
20171            }
20172            scheduleWritePackageRestrictionsLocked(userId);
20173            updateSequenceNumberLP(packageName, new int[] { userId });
20174            final long callingId = Binder.clearCallingIdentity();
20175            try {
20176                updateInstantAppInstallerLocked(packageName);
20177            } finally {
20178                Binder.restoreCallingIdentity(callingId);
20179            }
20180            components = mPendingBroadcasts.get(userId, packageName);
20181            final boolean newPackage = components == null;
20182            if (newPackage) {
20183                components = new ArrayList<String>();
20184            }
20185            if (!components.contains(componentName)) {
20186                components.add(componentName);
20187            }
20188            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20189                sendNow = true;
20190                // Purge entry from pending broadcast list if another one exists already
20191                // since we are sending one right away.
20192                mPendingBroadcasts.remove(userId, packageName);
20193            } else {
20194                if (newPackage) {
20195                    mPendingBroadcasts.put(userId, packageName, components);
20196                }
20197                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20198                    // Schedule a message
20199                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20200                }
20201            }
20202        }
20203
20204        long callingId = Binder.clearCallingIdentity();
20205        try {
20206            if (sendNow) {
20207                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20208                sendPackageChangedBroadcast(packageName,
20209                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20210            }
20211        } finally {
20212            Binder.restoreCallingIdentity(callingId);
20213        }
20214    }
20215
20216    @Override
20217    public void flushPackageRestrictionsAsUser(int userId) {
20218        if (!sUserManager.exists(userId)) {
20219            return;
20220        }
20221        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20222                false /* checkShell */, "flushPackageRestrictions");
20223        synchronized (mPackages) {
20224            mSettings.writePackageRestrictionsLPr(userId);
20225            mDirtyUsers.remove(userId);
20226            if (mDirtyUsers.isEmpty()) {
20227                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20228            }
20229        }
20230    }
20231
20232    private void sendPackageChangedBroadcast(String packageName,
20233            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20234        if (DEBUG_INSTALL)
20235            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20236                    + componentNames);
20237        Bundle extras = new Bundle(4);
20238        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20239        String nameList[] = new String[componentNames.size()];
20240        componentNames.toArray(nameList);
20241        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20242        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20243        extras.putInt(Intent.EXTRA_UID, packageUid);
20244        // If this is not reporting a change of the overall package, then only send it
20245        // to registered receivers.  We don't want to launch a swath of apps for every
20246        // little component state change.
20247        final int flags = !componentNames.contains(packageName)
20248                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20249        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20250                new int[] {UserHandle.getUserId(packageUid)});
20251    }
20252
20253    @Override
20254    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20255        if (!sUserManager.exists(userId)) return;
20256        final int uid = Binder.getCallingUid();
20257        final int permission = mContext.checkCallingOrSelfPermission(
20258                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20259        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20260        enforceCrossUserPermission(uid, userId,
20261                true /* requireFullPermission */, true /* checkShell */, "stop package");
20262        // writer
20263        synchronized (mPackages) {
20264            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20265                    allowedByPermission, uid, userId)) {
20266                scheduleWritePackageRestrictionsLocked(userId);
20267            }
20268        }
20269    }
20270
20271    @Override
20272    public String getInstallerPackageName(String packageName) {
20273        // reader
20274        synchronized (mPackages) {
20275            return mSettings.getInstallerPackageNameLPr(packageName);
20276        }
20277    }
20278
20279    public boolean isOrphaned(String packageName) {
20280        // reader
20281        synchronized (mPackages) {
20282            return mSettings.isOrphaned(packageName);
20283        }
20284    }
20285
20286    @Override
20287    public int getApplicationEnabledSetting(String packageName, int userId) {
20288        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20289        int uid = Binder.getCallingUid();
20290        enforceCrossUserPermission(uid, userId,
20291                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20292        // reader
20293        synchronized (mPackages) {
20294            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20295        }
20296    }
20297
20298    @Override
20299    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20300        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20301        int uid = Binder.getCallingUid();
20302        enforceCrossUserPermission(uid, userId,
20303                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20304        // reader
20305        synchronized (mPackages) {
20306            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20307        }
20308    }
20309
20310    @Override
20311    public void enterSafeMode() {
20312        enforceSystemOrRoot("Only the system can request entering safe mode");
20313
20314        if (!mSystemReady) {
20315            mSafeMode = true;
20316        }
20317    }
20318
20319    @Override
20320    public void systemReady() {
20321        mSystemReady = true;
20322        final ContentResolver resolver = mContext.getContentResolver();
20323        ContentObserver co = new ContentObserver(mHandler) {
20324            @Override
20325            public void onChange(boolean selfChange) {
20326                mEphemeralAppsDisabled =
20327                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20328                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20329            }
20330        };
20331        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20332                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20333                false, co, UserHandle.USER_SYSTEM);
20334        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20335                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20336        co.onChange(true);
20337
20338        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20339        // disabled after already being started.
20340        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20341                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20342
20343        // Read the compatibilty setting when the system is ready.
20344        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20345                mContext.getContentResolver(),
20346                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20347        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20348        if (DEBUG_SETTINGS) {
20349            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20350        }
20351
20352        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20353
20354        synchronized (mPackages) {
20355            // Verify that all of the preferred activity components actually
20356            // exist.  It is possible for applications to be updated and at
20357            // that point remove a previously declared activity component that
20358            // had been set as a preferred activity.  We try to clean this up
20359            // the next time we encounter that preferred activity, but it is
20360            // possible for the user flow to never be able to return to that
20361            // situation so here we do a sanity check to make sure we haven't
20362            // left any junk around.
20363            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20364            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20365                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20366                removed.clear();
20367                for (PreferredActivity pa : pir.filterSet()) {
20368                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20369                        removed.add(pa);
20370                    }
20371                }
20372                if (removed.size() > 0) {
20373                    for (int r=0; r<removed.size(); r++) {
20374                        PreferredActivity pa = removed.get(r);
20375                        Slog.w(TAG, "Removing dangling preferred activity: "
20376                                + pa.mPref.mComponent);
20377                        pir.removeFilter(pa);
20378                    }
20379                    mSettings.writePackageRestrictionsLPr(
20380                            mSettings.mPreferredActivities.keyAt(i));
20381                }
20382            }
20383
20384            for (int userId : UserManagerService.getInstance().getUserIds()) {
20385                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20386                    grantPermissionsUserIds = ArrayUtils.appendInt(
20387                            grantPermissionsUserIds, userId);
20388                }
20389            }
20390        }
20391        sUserManager.systemReady();
20392
20393        // If we upgraded grant all default permissions before kicking off.
20394        for (int userId : grantPermissionsUserIds) {
20395            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20396        }
20397
20398        // If we did not grant default permissions, we preload from this the
20399        // default permission exceptions lazily to ensure we don't hit the
20400        // disk on a new user creation.
20401        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20402            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20403        }
20404
20405        // Kick off any messages waiting for system ready
20406        if (mPostSystemReadyMessages != null) {
20407            for (Message msg : mPostSystemReadyMessages) {
20408                msg.sendToTarget();
20409            }
20410            mPostSystemReadyMessages = null;
20411        }
20412
20413        // Watch for external volumes that come and go over time
20414        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20415        storage.registerListener(mStorageListener);
20416
20417        mInstallerService.systemReady();
20418        mPackageDexOptimizer.systemReady();
20419
20420        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20421                StorageManagerInternal.class);
20422        StorageManagerInternal.addExternalStoragePolicy(
20423                new StorageManagerInternal.ExternalStorageMountPolicy() {
20424            @Override
20425            public int getMountMode(int uid, String packageName) {
20426                if (Process.isIsolated(uid)) {
20427                    return Zygote.MOUNT_EXTERNAL_NONE;
20428                }
20429                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20430                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20431                }
20432                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20433                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20434                }
20435                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20436                    return Zygote.MOUNT_EXTERNAL_READ;
20437                }
20438                return Zygote.MOUNT_EXTERNAL_WRITE;
20439            }
20440
20441            @Override
20442            public boolean hasExternalStorage(int uid, String packageName) {
20443                return true;
20444            }
20445        });
20446
20447        // Now that we're mostly running, clean up stale users and apps
20448        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20449        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20450
20451        if (mPrivappPermissionsViolations != null) {
20452            Slog.wtf(TAG,"Signature|privileged permissions not in "
20453                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20454            mPrivappPermissionsViolations = null;
20455        }
20456    }
20457
20458    public void waitForAppDataPrepared() {
20459        if (mPrepareAppDataFuture == null) {
20460            return;
20461        }
20462        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20463        mPrepareAppDataFuture = null;
20464    }
20465
20466    @Override
20467    public boolean isSafeMode() {
20468        return mSafeMode;
20469    }
20470
20471    @Override
20472    public boolean hasSystemUidErrors() {
20473        return mHasSystemUidErrors;
20474    }
20475
20476    static String arrayToString(int[] array) {
20477        StringBuffer buf = new StringBuffer(128);
20478        buf.append('[');
20479        if (array != null) {
20480            for (int i=0; i<array.length; i++) {
20481                if (i > 0) buf.append(", ");
20482                buf.append(array[i]);
20483            }
20484        }
20485        buf.append(']');
20486        return buf.toString();
20487    }
20488
20489    static class DumpState {
20490        public static final int DUMP_LIBS = 1 << 0;
20491        public static final int DUMP_FEATURES = 1 << 1;
20492        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20493        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20494        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20495        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20496        public static final int DUMP_PERMISSIONS = 1 << 6;
20497        public static final int DUMP_PACKAGES = 1 << 7;
20498        public static final int DUMP_SHARED_USERS = 1 << 8;
20499        public static final int DUMP_MESSAGES = 1 << 9;
20500        public static final int DUMP_PROVIDERS = 1 << 10;
20501        public static final int DUMP_VERIFIERS = 1 << 11;
20502        public static final int DUMP_PREFERRED = 1 << 12;
20503        public static final int DUMP_PREFERRED_XML = 1 << 13;
20504        public static final int DUMP_KEYSETS = 1 << 14;
20505        public static final int DUMP_VERSION = 1 << 15;
20506        public static final int DUMP_INSTALLS = 1 << 16;
20507        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20508        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20509        public static final int DUMP_FROZEN = 1 << 19;
20510        public static final int DUMP_DEXOPT = 1 << 20;
20511        public static final int DUMP_COMPILER_STATS = 1 << 21;
20512        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20513
20514        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20515
20516        private int mTypes;
20517
20518        private int mOptions;
20519
20520        private boolean mTitlePrinted;
20521
20522        private SharedUserSetting mSharedUser;
20523
20524        public boolean isDumping(int type) {
20525            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20526                return true;
20527            }
20528
20529            return (mTypes & type) != 0;
20530        }
20531
20532        public void setDump(int type) {
20533            mTypes |= type;
20534        }
20535
20536        public boolean isOptionEnabled(int option) {
20537            return (mOptions & option) != 0;
20538        }
20539
20540        public void setOptionEnabled(int option) {
20541            mOptions |= option;
20542        }
20543
20544        public boolean onTitlePrinted() {
20545            final boolean printed = mTitlePrinted;
20546            mTitlePrinted = true;
20547            return printed;
20548        }
20549
20550        public boolean getTitlePrinted() {
20551            return mTitlePrinted;
20552        }
20553
20554        public void setTitlePrinted(boolean enabled) {
20555            mTitlePrinted = enabled;
20556        }
20557
20558        public SharedUserSetting getSharedUser() {
20559            return mSharedUser;
20560        }
20561
20562        public void setSharedUser(SharedUserSetting user) {
20563            mSharedUser = user;
20564        }
20565    }
20566
20567    @Override
20568    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20569            FileDescriptor err, String[] args, ShellCallback callback,
20570            ResultReceiver resultReceiver) {
20571        (new PackageManagerShellCommand(this)).exec(
20572                this, in, out, err, args, callback, resultReceiver);
20573    }
20574
20575    @Override
20576    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20577        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20578
20579        DumpState dumpState = new DumpState();
20580        boolean fullPreferred = false;
20581        boolean checkin = false;
20582
20583        String packageName = null;
20584        ArraySet<String> permissionNames = null;
20585
20586        int opti = 0;
20587        while (opti < args.length) {
20588            String opt = args[opti];
20589            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20590                break;
20591            }
20592            opti++;
20593
20594            if ("-a".equals(opt)) {
20595                // Right now we only know how to print all.
20596            } else if ("-h".equals(opt)) {
20597                pw.println("Package manager dump options:");
20598                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20599                pw.println("    --checkin: dump for a checkin");
20600                pw.println("    -f: print details of intent filters");
20601                pw.println("    -h: print this help");
20602                pw.println("  cmd may be one of:");
20603                pw.println("    l[ibraries]: list known shared libraries");
20604                pw.println("    f[eatures]: list device features");
20605                pw.println("    k[eysets]: print known keysets");
20606                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20607                pw.println("    perm[issions]: dump permissions");
20608                pw.println("    permission [name ...]: dump declaration and use of given permission");
20609                pw.println("    pref[erred]: print preferred package settings");
20610                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20611                pw.println("    prov[iders]: dump content providers");
20612                pw.println("    p[ackages]: dump installed packages");
20613                pw.println("    s[hared-users]: dump shared user IDs");
20614                pw.println("    m[essages]: print collected runtime messages");
20615                pw.println("    v[erifiers]: print package verifier info");
20616                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20617                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20618                pw.println("    version: print database version info");
20619                pw.println("    write: write current settings now");
20620                pw.println("    installs: details about install sessions");
20621                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20622                pw.println("    dexopt: dump dexopt state");
20623                pw.println("    compiler-stats: dump compiler statistics");
20624                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20625                pw.println("    <package.name>: info about given package");
20626                return;
20627            } else if ("--checkin".equals(opt)) {
20628                checkin = true;
20629            } else if ("-f".equals(opt)) {
20630                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20631            } else if ("--proto".equals(opt)) {
20632                dumpProto(fd);
20633                return;
20634            } else {
20635                pw.println("Unknown argument: " + opt + "; use -h for help");
20636            }
20637        }
20638
20639        // Is the caller requesting to dump a particular piece of data?
20640        if (opti < args.length) {
20641            String cmd = args[opti];
20642            opti++;
20643            // Is this a package name?
20644            if ("android".equals(cmd) || cmd.contains(".")) {
20645                packageName = cmd;
20646                // When dumping a single package, we always dump all of its
20647                // filter information since the amount of data will be reasonable.
20648                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20649            } else if ("check-permission".equals(cmd)) {
20650                if (opti >= args.length) {
20651                    pw.println("Error: check-permission missing permission argument");
20652                    return;
20653                }
20654                String perm = args[opti];
20655                opti++;
20656                if (opti >= args.length) {
20657                    pw.println("Error: check-permission missing package argument");
20658                    return;
20659                }
20660
20661                String pkg = args[opti];
20662                opti++;
20663                int user = UserHandle.getUserId(Binder.getCallingUid());
20664                if (opti < args.length) {
20665                    try {
20666                        user = Integer.parseInt(args[opti]);
20667                    } catch (NumberFormatException e) {
20668                        pw.println("Error: check-permission user argument is not a number: "
20669                                + args[opti]);
20670                        return;
20671                    }
20672                }
20673
20674                // Normalize package name to handle renamed packages and static libs
20675                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20676
20677                pw.println(checkPermission(perm, pkg, user));
20678                return;
20679            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20680                dumpState.setDump(DumpState.DUMP_LIBS);
20681            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20682                dumpState.setDump(DumpState.DUMP_FEATURES);
20683            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20684                if (opti >= args.length) {
20685                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20686                            | DumpState.DUMP_SERVICE_RESOLVERS
20687                            | DumpState.DUMP_RECEIVER_RESOLVERS
20688                            | DumpState.DUMP_CONTENT_RESOLVERS);
20689                } else {
20690                    while (opti < args.length) {
20691                        String name = args[opti];
20692                        if ("a".equals(name) || "activity".equals(name)) {
20693                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20694                        } else if ("s".equals(name) || "service".equals(name)) {
20695                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20696                        } else if ("r".equals(name) || "receiver".equals(name)) {
20697                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20698                        } else if ("c".equals(name) || "content".equals(name)) {
20699                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20700                        } else {
20701                            pw.println("Error: unknown resolver table type: " + name);
20702                            return;
20703                        }
20704                        opti++;
20705                    }
20706                }
20707            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20708                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20709            } else if ("permission".equals(cmd)) {
20710                if (opti >= args.length) {
20711                    pw.println("Error: permission requires permission name");
20712                    return;
20713                }
20714                permissionNames = new ArraySet<>();
20715                while (opti < args.length) {
20716                    permissionNames.add(args[opti]);
20717                    opti++;
20718                }
20719                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20720                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20721            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20722                dumpState.setDump(DumpState.DUMP_PREFERRED);
20723            } else if ("preferred-xml".equals(cmd)) {
20724                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20725                if (opti < args.length && "--full".equals(args[opti])) {
20726                    fullPreferred = true;
20727                    opti++;
20728                }
20729            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20730                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20731            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20732                dumpState.setDump(DumpState.DUMP_PACKAGES);
20733            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20734                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20735            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20736                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20737            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20738                dumpState.setDump(DumpState.DUMP_MESSAGES);
20739            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20740                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20741            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20742                    || "intent-filter-verifiers".equals(cmd)) {
20743                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20744            } else if ("version".equals(cmd)) {
20745                dumpState.setDump(DumpState.DUMP_VERSION);
20746            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20747                dumpState.setDump(DumpState.DUMP_KEYSETS);
20748            } else if ("installs".equals(cmd)) {
20749                dumpState.setDump(DumpState.DUMP_INSTALLS);
20750            } else if ("frozen".equals(cmd)) {
20751                dumpState.setDump(DumpState.DUMP_FROZEN);
20752            } else if ("dexopt".equals(cmd)) {
20753                dumpState.setDump(DumpState.DUMP_DEXOPT);
20754            } else if ("compiler-stats".equals(cmd)) {
20755                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20756            } else if ("enabled-overlays".equals(cmd)) {
20757                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20758            } else if ("write".equals(cmd)) {
20759                synchronized (mPackages) {
20760                    mSettings.writeLPr();
20761                    pw.println("Settings written.");
20762                    return;
20763                }
20764            }
20765        }
20766
20767        if (checkin) {
20768            pw.println("vers,1");
20769        }
20770
20771        // reader
20772        synchronized (mPackages) {
20773            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20774                if (!checkin) {
20775                    if (dumpState.onTitlePrinted())
20776                        pw.println();
20777                    pw.println("Database versions:");
20778                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20779                }
20780            }
20781
20782            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20783                if (!checkin) {
20784                    if (dumpState.onTitlePrinted())
20785                        pw.println();
20786                    pw.println("Verifiers:");
20787                    pw.print("  Required: ");
20788                    pw.print(mRequiredVerifierPackage);
20789                    pw.print(" (uid=");
20790                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20791                            UserHandle.USER_SYSTEM));
20792                    pw.println(")");
20793                } else if (mRequiredVerifierPackage != null) {
20794                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20795                    pw.print(",");
20796                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20797                            UserHandle.USER_SYSTEM));
20798                }
20799            }
20800
20801            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20802                    packageName == null) {
20803                if (mIntentFilterVerifierComponent != null) {
20804                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20805                    if (!checkin) {
20806                        if (dumpState.onTitlePrinted())
20807                            pw.println();
20808                        pw.println("Intent Filter Verifier:");
20809                        pw.print("  Using: ");
20810                        pw.print(verifierPackageName);
20811                        pw.print(" (uid=");
20812                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20813                                UserHandle.USER_SYSTEM));
20814                        pw.println(")");
20815                    } else if (verifierPackageName != null) {
20816                        pw.print("ifv,"); pw.print(verifierPackageName);
20817                        pw.print(",");
20818                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20819                                UserHandle.USER_SYSTEM));
20820                    }
20821                } else {
20822                    pw.println();
20823                    pw.println("No Intent Filter Verifier available!");
20824                }
20825            }
20826
20827            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20828                boolean printedHeader = false;
20829                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20830                while (it.hasNext()) {
20831                    String libName = it.next();
20832                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20833                    if (versionedLib == null) {
20834                        continue;
20835                    }
20836                    final int versionCount = versionedLib.size();
20837                    for (int i = 0; i < versionCount; i++) {
20838                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20839                        if (!checkin) {
20840                            if (!printedHeader) {
20841                                if (dumpState.onTitlePrinted())
20842                                    pw.println();
20843                                pw.println("Libraries:");
20844                                printedHeader = true;
20845                            }
20846                            pw.print("  ");
20847                        } else {
20848                            pw.print("lib,");
20849                        }
20850                        pw.print(libEntry.info.getName());
20851                        if (libEntry.info.isStatic()) {
20852                            pw.print(" version=" + libEntry.info.getVersion());
20853                        }
20854                        if (!checkin) {
20855                            pw.print(" -> ");
20856                        }
20857                        if (libEntry.path != null) {
20858                            pw.print(" (jar) ");
20859                            pw.print(libEntry.path);
20860                        } else {
20861                            pw.print(" (apk) ");
20862                            pw.print(libEntry.apk);
20863                        }
20864                        pw.println();
20865                    }
20866                }
20867            }
20868
20869            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20870                if (dumpState.onTitlePrinted())
20871                    pw.println();
20872                if (!checkin) {
20873                    pw.println("Features:");
20874                }
20875
20876                synchronized (mAvailableFeatures) {
20877                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20878                        if (checkin) {
20879                            pw.print("feat,");
20880                            pw.print(feat.name);
20881                            pw.print(",");
20882                            pw.println(feat.version);
20883                        } else {
20884                            pw.print("  ");
20885                            pw.print(feat.name);
20886                            if (feat.version > 0) {
20887                                pw.print(" version=");
20888                                pw.print(feat.version);
20889                            }
20890                            pw.println();
20891                        }
20892                    }
20893                }
20894            }
20895
20896            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20897                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20898                        : "Activity Resolver Table:", "  ", packageName,
20899                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20900                    dumpState.setTitlePrinted(true);
20901                }
20902            }
20903            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20904                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20905                        : "Receiver Resolver Table:", "  ", packageName,
20906                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20907                    dumpState.setTitlePrinted(true);
20908                }
20909            }
20910            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20911                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20912                        : "Service Resolver Table:", "  ", packageName,
20913                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20914                    dumpState.setTitlePrinted(true);
20915                }
20916            }
20917            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20918                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20919                        : "Provider Resolver Table:", "  ", packageName,
20920                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20921                    dumpState.setTitlePrinted(true);
20922                }
20923            }
20924
20925            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20926                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20927                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20928                    int user = mSettings.mPreferredActivities.keyAt(i);
20929                    if (pir.dump(pw,
20930                            dumpState.getTitlePrinted()
20931                                ? "\nPreferred Activities User " + user + ":"
20932                                : "Preferred Activities User " + user + ":", "  ",
20933                            packageName, true, false)) {
20934                        dumpState.setTitlePrinted(true);
20935                    }
20936                }
20937            }
20938
20939            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20940                pw.flush();
20941                FileOutputStream fout = new FileOutputStream(fd);
20942                BufferedOutputStream str = new BufferedOutputStream(fout);
20943                XmlSerializer serializer = new FastXmlSerializer();
20944                try {
20945                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20946                    serializer.startDocument(null, true);
20947                    serializer.setFeature(
20948                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20949                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20950                    serializer.endDocument();
20951                    serializer.flush();
20952                } catch (IllegalArgumentException e) {
20953                    pw.println("Failed writing: " + e);
20954                } catch (IllegalStateException e) {
20955                    pw.println("Failed writing: " + e);
20956                } catch (IOException e) {
20957                    pw.println("Failed writing: " + e);
20958                }
20959            }
20960
20961            if (!checkin
20962                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20963                    && packageName == null) {
20964                pw.println();
20965                int count = mSettings.mPackages.size();
20966                if (count == 0) {
20967                    pw.println("No applications!");
20968                    pw.println();
20969                } else {
20970                    final String prefix = "  ";
20971                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20972                    if (allPackageSettings.size() == 0) {
20973                        pw.println("No domain preferred apps!");
20974                        pw.println();
20975                    } else {
20976                        pw.println("App verification status:");
20977                        pw.println();
20978                        count = 0;
20979                        for (PackageSetting ps : allPackageSettings) {
20980                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20981                            if (ivi == null || ivi.getPackageName() == null) continue;
20982                            pw.println(prefix + "Package: " + ivi.getPackageName());
20983                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20984                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20985                            pw.println();
20986                            count++;
20987                        }
20988                        if (count == 0) {
20989                            pw.println(prefix + "No app verification established.");
20990                            pw.println();
20991                        }
20992                        for (int userId : sUserManager.getUserIds()) {
20993                            pw.println("App linkages for user " + userId + ":");
20994                            pw.println();
20995                            count = 0;
20996                            for (PackageSetting ps : allPackageSettings) {
20997                                final long status = ps.getDomainVerificationStatusForUser(userId);
20998                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20999                                        && !DEBUG_DOMAIN_VERIFICATION) {
21000                                    continue;
21001                                }
21002                                pw.println(prefix + "Package: " + ps.name);
21003                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21004                                String statusStr = IntentFilterVerificationInfo.
21005                                        getStatusStringFromValue(status);
21006                                pw.println(prefix + "Status:  " + statusStr);
21007                                pw.println();
21008                                count++;
21009                            }
21010                            if (count == 0) {
21011                                pw.println(prefix + "No configured app linkages.");
21012                                pw.println();
21013                            }
21014                        }
21015                    }
21016                }
21017            }
21018
21019            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21020                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21021                if (packageName == null && permissionNames == null) {
21022                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21023                        if (iperm == 0) {
21024                            if (dumpState.onTitlePrinted())
21025                                pw.println();
21026                            pw.println("AppOp Permissions:");
21027                        }
21028                        pw.print("  AppOp Permission ");
21029                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21030                        pw.println(":");
21031                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21032                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21033                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21034                        }
21035                    }
21036                }
21037            }
21038
21039            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21040                boolean printedSomething = false;
21041                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21042                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21043                        continue;
21044                    }
21045                    if (!printedSomething) {
21046                        if (dumpState.onTitlePrinted())
21047                            pw.println();
21048                        pw.println("Registered ContentProviders:");
21049                        printedSomething = true;
21050                    }
21051                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21052                    pw.print("    "); pw.println(p.toString());
21053                }
21054                printedSomething = false;
21055                for (Map.Entry<String, PackageParser.Provider> entry :
21056                        mProvidersByAuthority.entrySet()) {
21057                    PackageParser.Provider p = entry.getValue();
21058                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21059                        continue;
21060                    }
21061                    if (!printedSomething) {
21062                        if (dumpState.onTitlePrinted())
21063                            pw.println();
21064                        pw.println("ContentProvider Authorities:");
21065                        printedSomething = true;
21066                    }
21067                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21068                    pw.print("    "); pw.println(p.toString());
21069                    if (p.info != null && p.info.applicationInfo != null) {
21070                        final String appInfo = p.info.applicationInfo.toString();
21071                        pw.print("      applicationInfo="); pw.println(appInfo);
21072                    }
21073                }
21074            }
21075
21076            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21077                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21078            }
21079
21080            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21081                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21082            }
21083
21084            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21085                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21086            }
21087
21088            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21089                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21090            }
21091
21092            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21093                // XXX should handle packageName != null by dumping only install data that
21094                // the given package is involved with.
21095                if (dumpState.onTitlePrinted()) pw.println();
21096
21097                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21098                ipw.println();
21099                ipw.println("Frozen packages:");
21100                ipw.increaseIndent();
21101                if (mFrozenPackages.size() == 0) {
21102                    ipw.println("(none)");
21103                } else {
21104                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21105                        ipw.println(mFrozenPackages.valueAt(i));
21106                    }
21107                }
21108                ipw.decreaseIndent();
21109            }
21110
21111            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21112                if (dumpState.onTitlePrinted()) pw.println();
21113                dumpDexoptStateLPr(pw, packageName);
21114            }
21115
21116            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21117                if (dumpState.onTitlePrinted()) pw.println();
21118                dumpCompilerStatsLPr(pw, packageName);
21119            }
21120
21121            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21122                if (dumpState.onTitlePrinted()) pw.println();
21123                dumpEnabledOverlaysLPr(pw);
21124            }
21125
21126            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21127                if (dumpState.onTitlePrinted()) pw.println();
21128                mSettings.dumpReadMessagesLPr(pw, dumpState);
21129
21130                pw.println();
21131                pw.println("Package warning messages:");
21132                BufferedReader in = null;
21133                String line = null;
21134                try {
21135                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21136                    while ((line = in.readLine()) != null) {
21137                        if (line.contains("ignored: updated version")) continue;
21138                        pw.println(line);
21139                    }
21140                } catch (IOException ignored) {
21141                } finally {
21142                    IoUtils.closeQuietly(in);
21143                }
21144            }
21145
21146            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21147                BufferedReader in = null;
21148                String line = null;
21149                try {
21150                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21151                    while ((line = in.readLine()) != null) {
21152                        if (line.contains("ignored: updated version")) continue;
21153                        pw.print("msg,");
21154                        pw.println(line);
21155                    }
21156                } catch (IOException ignored) {
21157                } finally {
21158                    IoUtils.closeQuietly(in);
21159                }
21160            }
21161        }
21162
21163        // PackageInstaller should be called outside of mPackages lock
21164        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21165            // XXX should handle packageName != null by dumping only install data that
21166            // the given package is involved with.
21167            if (dumpState.onTitlePrinted()) pw.println();
21168            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21169        }
21170    }
21171
21172    private void dumpProto(FileDescriptor fd) {
21173        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21174
21175        synchronized (mPackages) {
21176            final long requiredVerifierPackageToken =
21177                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21178            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21179            proto.write(
21180                    PackageServiceDumpProto.PackageShortProto.UID,
21181                    getPackageUid(
21182                            mRequiredVerifierPackage,
21183                            MATCH_DEBUG_TRIAGED_MISSING,
21184                            UserHandle.USER_SYSTEM));
21185            proto.end(requiredVerifierPackageToken);
21186
21187            if (mIntentFilterVerifierComponent != null) {
21188                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21189                final long verifierPackageToken =
21190                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21191                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21192                proto.write(
21193                        PackageServiceDumpProto.PackageShortProto.UID,
21194                        getPackageUid(
21195                                verifierPackageName,
21196                                MATCH_DEBUG_TRIAGED_MISSING,
21197                                UserHandle.USER_SYSTEM));
21198                proto.end(verifierPackageToken);
21199            }
21200
21201            dumpSharedLibrariesProto(proto);
21202            dumpFeaturesProto(proto);
21203            mSettings.dumpPackagesProto(proto);
21204            mSettings.dumpSharedUsersProto(proto);
21205            dumpMessagesProto(proto);
21206        }
21207        proto.flush();
21208    }
21209
21210    private void dumpMessagesProto(ProtoOutputStream proto) {
21211        BufferedReader in = null;
21212        String line = null;
21213        try {
21214            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21215            while ((line = in.readLine()) != null) {
21216                if (line.contains("ignored: updated version")) continue;
21217                proto.write(PackageServiceDumpProto.MESSAGES, line);
21218            }
21219        } catch (IOException ignored) {
21220        } finally {
21221            IoUtils.closeQuietly(in);
21222        }
21223    }
21224
21225    private void dumpFeaturesProto(ProtoOutputStream proto) {
21226        synchronized (mAvailableFeatures) {
21227            final int count = mAvailableFeatures.size();
21228            for (int i = 0; i < count; i++) {
21229                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21230                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21231                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21232                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21233                proto.end(featureToken);
21234            }
21235        }
21236    }
21237
21238    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21239        final int count = mSharedLibraries.size();
21240        for (int i = 0; i < count; i++) {
21241            final String libName = mSharedLibraries.keyAt(i);
21242            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21243            if (versionedLib == null) {
21244                continue;
21245            }
21246            final int versionCount = versionedLib.size();
21247            for (int j = 0; j < versionCount; j++) {
21248                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21249                final long sharedLibraryToken =
21250                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21251                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21252                final boolean isJar = (libEntry.path != null);
21253                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21254                if (isJar) {
21255                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21256                } else {
21257                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21258                }
21259                proto.end(sharedLibraryToken);
21260            }
21261        }
21262    }
21263
21264    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21265        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21266        ipw.println();
21267        ipw.println("Dexopt state:");
21268        ipw.increaseIndent();
21269        Collection<PackageParser.Package> packages = null;
21270        if (packageName != null) {
21271            PackageParser.Package targetPackage = mPackages.get(packageName);
21272            if (targetPackage != null) {
21273                packages = Collections.singletonList(targetPackage);
21274            } else {
21275                ipw.println("Unable to find package: " + packageName);
21276                return;
21277            }
21278        } else {
21279            packages = mPackages.values();
21280        }
21281
21282        for (PackageParser.Package pkg : packages) {
21283            ipw.println("[" + pkg.packageName + "]");
21284            ipw.increaseIndent();
21285            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21286            ipw.decreaseIndent();
21287        }
21288    }
21289
21290    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21291        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21292        ipw.println();
21293        ipw.println("Compiler stats:");
21294        ipw.increaseIndent();
21295        Collection<PackageParser.Package> packages = null;
21296        if (packageName != null) {
21297            PackageParser.Package targetPackage = mPackages.get(packageName);
21298            if (targetPackage != null) {
21299                packages = Collections.singletonList(targetPackage);
21300            } else {
21301                ipw.println("Unable to find package: " + packageName);
21302                return;
21303            }
21304        } else {
21305            packages = mPackages.values();
21306        }
21307
21308        for (PackageParser.Package pkg : packages) {
21309            ipw.println("[" + pkg.packageName + "]");
21310            ipw.increaseIndent();
21311
21312            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21313            if (stats == null) {
21314                ipw.println("(No recorded stats)");
21315            } else {
21316                stats.dump(ipw);
21317            }
21318            ipw.decreaseIndent();
21319        }
21320    }
21321
21322    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21323        pw.println("Enabled overlay paths:");
21324        final int N = mEnabledOverlayPaths.size();
21325        for (int i = 0; i < N; i++) {
21326            final int userId = mEnabledOverlayPaths.keyAt(i);
21327            pw.println(String.format("    User %d:", userId));
21328            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21329                mEnabledOverlayPaths.valueAt(i);
21330            final int M = userSpecificOverlays.size();
21331            for (int j = 0; j < M; j++) {
21332                final String targetPackageName = userSpecificOverlays.keyAt(j);
21333                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21334                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21335            }
21336        }
21337    }
21338
21339    private String dumpDomainString(String packageName) {
21340        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21341                .getList();
21342        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21343
21344        ArraySet<String> result = new ArraySet<>();
21345        if (iviList.size() > 0) {
21346            for (IntentFilterVerificationInfo ivi : iviList) {
21347                for (String host : ivi.getDomains()) {
21348                    result.add(host);
21349                }
21350            }
21351        }
21352        if (filters != null && filters.size() > 0) {
21353            for (IntentFilter filter : filters) {
21354                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21355                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21356                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21357                    result.addAll(filter.getHostsList());
21358                }
21359            }
21360        }
21361
21362        StringBuilder sb = new StringBuilder(result.size() * 16);
21363        for (String domain : result) {
21364            if (sb.length() > 0) sb.append(" ");
21365            sb.append(domain);
21366        }
21367        return sb.toString();
21368    }
21369
21370    // ------- apps on sdcard specific code -------
21371    static final boolean DEBUG_SD_INSTALL = false;
21372
21373    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21374
21375    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21376
21377    private boolean mMediaMounted = false;
21378
21379    static String getEncryptKey() {
21380        try {
21381            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21382                    SD_ENCRYPTION_KEYSTORE_NAME);
21383            if (sdEncKey == null) {
21384                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21385                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21386                if (sdEncKey == null) {
21387                    Slog.e(TAG, "Failed to create encryption keys");
21388                    return null;
21389                }
21390            }
21391            return sdEncKey;
21392        } catch (NoSuchAlgorithmException nsae) {
21393            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21394            return null;
21395        } catch (IOException ioe) {
21396            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21397            return null;
21398        }
21399    }
21400
21401    /*
21402     * Update media status on PackageManager.
21403     */
21404    @Override
21405    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21406        int callingUid = Binder.getCallingUid();
21407        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21408            throw new SecurityException("Media status can only be updated by the system");
21409        }
21410        // reader; this apparently protects mMediaMounted, but should probably
21411        // be a different lock in that case.
21412        synchronized (mPackages) {
21413            Log.i(TAG, "Updating external media status from "
21414                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21415                    + (mediaStatus ? "mounted" : "unmounted"));
21416            if (DEBUG_SD_INSTALL)
21417                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21418                        + ", mMediaMounted=" + mMediaMounted);
21419            if (mediaStatus == mMediaMounted) {
21420                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21421                        : 0, -1);
21422                mHandler.sendMessage(msg);
21423                return;
21424            }
21425            mMediaMounted = mediaStatus;
21426        }
21427        // Queue up an async operation since the package installation may take a
21428        // little while.
21429        mHandler.post(new Runnable() {
21430            public void run() {
21431                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21432            }
21433        });
21434    }
21435
21436    /**
21437     * Called by StorageManagerService when the initial ASECs to scan are available.
21438     * Should block until all the ASEC containers are finished being scanned.
21439     */
21440    public void scanAvailableAsecs() {
21441        updateExternalMediaStatusInner(true, false, false);
21442    }
21443
21444    /*
21445     * Collect information of applications on external media, map them against
21446     * existing containers and update information based on current mount status.
21447     * Please note that we always have to report status if reportStatus has been
21448     * set to true especially when unloading packages.
21449     */
21450    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21451            boolean externalStorage) {
21452        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21453        int[] uidArr = EmptyArray.INT;
21454
21455        final String[] list = PackageHelper.getSecureContainerList();
21456        if (ArrayUtils.isEmpty(list)) {
21457            Log.i(TAG, "No secure containers found");
21458        } else {
21459            // Process list of secure containers and categorize them
21460            // as active or stale based on their package internal state.
21461
21462            // reader
21463            synchronized (mPackages) {
21464                for (String cid : list) {
21465                    // Leave stages untouched for now; installer service owns them
21466                    if (PackageInstallerService.isStageName(cid)) continue;
21467
21468                    if (DEBUG_SD_INSTALL)
21469                        Log.i(TAG, "Processing container " + cid);
21470                    String pkgName = getAsecPackageName(cid);
21471                    if (pkgName == null) {
21472                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21473                        continue;
21474                    }
21475                    if (DEBUG_SD_INSTALL)
21476                        Log.i(TAG, "Looking for pkg : " + pkgName);
21477
21478                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21479                    if (ps == null) {
21480                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21481                        continue;
21482                    }
21483
21484                    /*
21485                     * Skip packages that are not external if we're unmounting
21486                     * external storage.
21487                     */
21488                    if (externalStorage && !isMounted && !isExternal(ps)) {
21489                        continue;
21490                    }
21491
21492                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21493                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21494                    // The package status is changed only if the code path
21495                    // matches between settings and the container id.
21496                    if (ps.codePathString != null
21497                            && ps.codePathString.startsWith(args.getCodePath())) {
21498                        if (DEBUG_SD_INSTALL) {
21499                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21500                                    + " at code path: " + ps.codePathString);
21501                        }
21502
21503                        // We do have a valid package installed on sdcard
21504                        processCids.put(args, ps.codePathString);
21505                        final int uid = ps.appId;
21506                        if (uid != -1) {
21507                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21508                        }
21509                    } else {
21510                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21511                                + ps.codePathString);
21512                    }
21513                }
21514            }
21515
21516            Arrays.sort(uidArr);
21517        }
21518
21519        // Process packages with valid entries.
21520        if (isMounted) {
21521            if (DEBUG_SD_INSTALL)
21522                Log.i(TAG, "Loading packages");
21523            loadMediaPackages(processCids, uidArr, externalStorage);
21524            startCleaningPackages();
21525            mInstallerService.onSecureContainersAvailable();
21526        } else {
21527            if (DEBUG_SD_INSTALL)
21528                Log.i(TAG, "Unloading packages");
21529            unloadMediaPackages(processCids, uidArr, reportStatus);
21530        }
21531    }
21532
21533    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21534            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21535        final int size = infos.size();
21536        final String[] packageNames = new String[size];
21537        final int[] packageUids = new int[size];
21538        for (int i = 0; i < size; i++) {
21539            final ApplicationInfo info = infos.get(i);
21540            packageNames[i] = info.packageName;
21541            packageUids[i] = info.uid;
21542        }
21543        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21544                finishedReceiver);
21545    }
21546
21547    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21548            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21549        sendResourcesChangedBroadcast(mediaStatus, replacing,
21550                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21551    }
21552
21553    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21554            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21555        int size = pkgList.length;
21556        if (size > 0) {
21557            // Send broadcasts here
21558            Bundle extras = new Bundle();
21559            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21560            if (uidArr != null) {
21561                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21562            }
21563            if (replacing) {
21564                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21565            }
21566            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21567                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21568            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21569        }
21570    }
21571
21572   /*
21573     * Look at potentially valid container ids from processCids If package
21574     * information doesn't match the one on record or package scanning fails,
21575     * the cid is added to list of removeCids. We currently don't delete stale
21576     * containers.
21577     */
21578    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21579            boolean externalStorage) {
21580        ArrayList<String> pkgList = new ArrayList<String>();
21581        Set<AsecInstallArgs> keys = processCids.keySet();
21582
21583        for (AsecInstallArgs args : keys) {
21584            String codePath = processCids.get(args);
21585            if (DEBUG_SD_INSTALL)
21586                Log.i(TAG, "Loading container : " + args.cid);
21587            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21588            try {
21589                // Make sure there are no container errors first.
21590                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21591                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21592                            + " when installing from sdcard");
21593                    continue;
21594                }
21595                // Check code path here.
21596                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21597                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21598                            + " does not match one in settings " + codePath);
21599                    continue;
21600                }
21601                // Parse package
21602                int parseFlags = mDefParseFlags;
21603                if (args.isExternalAsec()) {
21604                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21605                }
21606                if (args.isFwdLocked()) {
21607                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21608                }
21609
21610                synchronized (mInstallLock) {
21611                    PackageParser.Package pkg = null;
21612                    try {
21613                        // Sadly we don't know the package name yet to freeze it
21614                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21615                                SCAN_IGNORE_FROZEN, 0, null);
21616                    } catch (PackageManagerException e) {
21617                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21618                    }
21619                    // Scan the package
21620                    if (pkg != null) {
21621                        /*
21622                         * TODO why is the lock being held? doPostInstall is
21623                         * called in other places without the lock. This needs
21624                         * to be straightened out.
21625                         */
21626                        // writer
21627                        synchronized (mPackages) {
21628                            retCode = PackageManager.INSTALL_SUCCEEDED;
21629                            pkgList.add(pkg.packageName);
21630                            // Post process args
21631                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21632                                    pkg.applicationInfo.uid);
21633                        }
21634                    } else {
21635                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21636                    }
21637                }
21638
21639            } finally {
21640                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21641                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21642                }
21643            }
21644        }
21645        // writer
21646        synchronized (mPackages) {
21647            // If the platform SDK has changed since the last time we booted,
21648            // we need to re-grant app permission to catch any new ones that
21649            // appear. This is really a hack, and means that apps can in some
21650            // cases get permissions that the user didn't initially explicitly
21651            // allow... it would be nice to have some better way to handle
21652            // this situation.
21653            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21654                    : mSettings.getInternalVersion();
21655            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21656                    : StorageManager.UUID_PRIVATE_INTERNAL;
21657
21658            int updateFlags = UPDATE_PERMISSIONS_ALL;
21659            if (ver.sdkVersion != mSdkVersion) {
21660                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21661                        + mSdkVersion + "; regranting permissions for external");
21662                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21663            }
21664            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21665
21666            // Yay, everything is now upgraded
21667            ver.forceCurrent();
21668
21669            // can downgrade to reader
21670            // Persist settings
21671            mSettings.writeLPr();
21672        }
21673        // Send a broadcast to let everyone know we are done processing
21674        if (pkgList.size() > 0) {
21675            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21676        }
21677    }
21678
21679   /*
21680     * Utility method to unload a list of specified containers
21681     */
21682    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21683        // Just unmount all valid containers.
21684        for (AsecInstallArgs arg : cidArgs) {
21685            synchronized (mInstallLock) {
21686                arg.doPostDeleteLI(false);
21687           }
21688       }
21689   }
21690
21691    /*
21692     * Unload packages mounted on external media. This involves deleting package
21693     * data from internal structures, sending broadcasts about disabled packages,
21694     * gc'ing to free up references, unmounting all secure containers
21695     * corresponding to packages on external media, and posting a
21696     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21697     * that we always have to post this message if status has been requested no
21698     * matter what.
21699     */
21700    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21701            final boolean reportStatus) {
21702        if (DEBUG_SD_INSTALL)
21703            Log.i(TAG, "unloading media packages");
21704        ArrayList<String> pkgList = new ArrayList<String>();
21705        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21706        final Set<AsecInstallArgs> keys = processCids.keySet();
21707        for (AsecInstallArgs args : keys) {
21708            String pkgName = args.getPackageName();
21709            if (DEBUG_SD_INSTALL)
21710                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21711            // Delete package internally
21712            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21713            synchronized (mInstallLock) {
21714                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21715                final boolean res;
21716                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21717                        "unloadMediaPackages")) {
21718                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21719                            null);
21720                }
21721                if (res) {
21722                    pkgList.add(pkgName);
21723                } else {
21724                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21725                    failedList.add(args);
21726                }
21727            }
21728        }
21729
21730        // reader
21731        synchronized (mPackages) {
21732            // We didn't update the settings after removing each package;
21733            // write them now for all packages.
21734            mSettings.writeLPr();
21735        }
21736
21737        // We have to absolutely send UPDATED_MEDIA_STATUS only
21738        // after confirming that all the receivers processed the ordered
21739        // broadcast when packages get disabled, force a gc to clean things up.
21740        // and unload all the containers.
21741        if (pkgList.size() > 0) {
21742            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21743                    new IIntentReceiver.Stub() {
21744                public void performReceive(Intent intent, int resultCode, String data,
21745                        Bundle extras, boolean ordered, boolean sticky,
21746                        int sendingUser) throws RemoteException {
21747                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21748                            reportStatus ? 1 : 0, 1, keys);
21749                    mHandler.sendMessage(msg);
21750                }
21751            });
21752        } else {
21753            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21754                    keys);
21755            mHandler.sendMessage(msg);
21756        }
21757    }
21758
21759    private void loadPrivatePackages(final VolumeInfo vol) {
21760        mHandler.post(new Runnable() {
21761            @Override
21762            public void run() {
21763                loadPrivatePackagesInner(vol);
21764            }
21765        });
21766    }
21767
21768    private void loadPrivatePackagesInner(VolumeInfo vol) {
21769        final String volumeUuid = vol.fsUuid;
21770        if (TextUtils.isEmpty(volumeUuid)) {
21771            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21772            return;
21773        }
21774
21775        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21776        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21777        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21778
21779        final VersionInfo ver;
21780        final List<PackageSetting> packages;
21781        synchronized (mPackages) {
21782            ver = mSettings.findOrCreateVersion(volumeUuid);
21783            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21784        }
21785
21786        for (PackageSetting ps : packages) {
21787            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21788            synchronized (mInstallLock) {
21789                final PackageParser.Package pkg;
21790                try {
21791                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21792                    loaded.add(pkg.applicationInfo);
21793
21794                } catch (PackageManagerException e) {
21795                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21796                }
21797
21798                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21799                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21800                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21801                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21802                }
21803            }
21804        }
21805
21806        // Reconcile app data for all started/unlocked users
21807        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21808        final UserManager um = mContext.getSystemService(UserManager.class);
21809        UserManagerInternal umInternal = getUserManagerInternal();
21810        for (UserInfo user : um.getUsers()) {
21811            final int flags;
21812            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21813                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21814            } else if (umInternal.isUserRunning(user.id)) {
21815                flags = StorageManager.FLAG_STORAGE_DE;
21816            } else {
21817                continue;
21818            }
21819
21820            try {
21821                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21822                synchronized (mInstallLock) {
21823                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21824                }
21825            } catch (IllegalStateException e) {
21826                // Device was probably ejected, and we'll process that event momentarily
21827                Slog.w(TAG, "Failed to prepare storage: " + e);
21828            }
21829        }
21830
21831        synchronized (mPackages) {
21832            int updateFlags = UPDATE_PERMISSIONS_ALL;
21833            if (ver.sdkVersion != mSdkVersion) {
21834                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21835                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21836                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21837            }
21838            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21839
21840            // Yay, everything is now upgraded
21841            ver.forceCurrent();
21842
21843            mSettings.writeLPr();
21844        }
21845
21846        for (PackageFreezer freezer : freezers) {
21847            freezer.close();
21848        }
21849
21850        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21851        sendResourcesChangedBroadcast(true, false, loaded, null);
21852    }
21853
21854    private void unloadPrivatePackages(final VolumeInfo vol) {
21855        mHandler.post(new Runnable() {
21856            @Override
21857            public void run() {
21858                unloadPrivatePackagesInner(vol);
21859            }
21860        });
21861    }
21862
21863    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21864        final String volumeUuid = vol.fsUuid;
21865        if (TextUtils.isEmpty(volumeUuid)) {
21866            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21867            return;
21868        }
21869
21870        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21871        synchronized (mInstallLock) {
21872        synchronized (mPackages) {
21873            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21874            for (PackageSetting ps : packages) {
21875                if (ps.pkg == null) continue;
21876
21877                final ApplicationInfo info = ps.pkg.applicationInfo;
21878                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21879                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21880
21881                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21882                        "unloadPrivatePackagesInner")) {
21883                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21884                            false, null)) {
21885                        unloaded.add(info);
21886                    } else {
21887                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21888                    }
21889                }
21890
21891                // Try very hard to release any references to this package
21892                // so we don't risk the system server being killed due to
21893                // open FDs
21894                AttributeCache.instance().removePackage(ps.name);
21895            }
21896
21897            mSettings.writeLPr();
21898        }
21899        }
21900
21901        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21902        sendResourcesChangedBroadcast(false, false, unloaded, null);
21903
21904        // Try very hard to release any references to this path so we don't risk
21905        // the system server being killed due to open FDs
21906        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21907
21908        for (int i = 0; i < 3; i++) {
21909            System.gc();
21910            System.runFinalization();
21911        }
21912    }
21913
21914    private void assertPackageKnown(String volumeUuid, String packageName)
21915            throws PackageManagerException {
21916        synchronized (mPackages) {
21917            // Normalize package name to handle renamed packages
21918            packageName = normalizePackageNameLPr(packageName);
21919
21920            final PackageSetting ps = mSettings.mPackages.get(packageName);
21921            if (ps == null) {
21922                throw new PackageManagerException("Package " + packageName + " is unknown");
21923            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21924                throw new PackageManagerException(
21925                        "Package " + packageName + " found on unknown volume " + volumeUuid
21926                                + "; expected volume " + ps.volumeUuid);
21927            }
21928        }
21929    }
21930
21931    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21932            throws PackageManagerException {
21933        synchronized (mPackages) {
21934            // Normalize package name to handle renamed packages
21935            packageName = normalizePackageNameLPr(packageName);
21936
21937            final PackageSetting ps = mSettings.mPackages.get(packageName);
21938            if (ps == null) {
21939                throw new PackageManagerException("Package " + packageName + " is unknown");
21940            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21941                throw new PackageManagerException(
21942                        "Package " + packageName + " found on unknown volume " + volumeUuid
21943                                + "; expected volume " + ps.volumeUuid);
21944            } else if (!ps.getInstalled(userId)) {
21945                throw new PackageManagerException(
21946                        "Package " + packageName + " not installed for user " + userId);
21947            }
21948        }
21949    }
21950
21951    private List<String> collectAbsoluteCodePaths() {
21952        synchronized (mPackages) {
21953            List<String> codePaths = new ArrayList<>();
21954            final int packageCount = mSettings.mPackages.size();
21955            for (int i = 0; i < packageCount; i++) {
21956                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21957                codePaths.add(ps.codePath.getAbsolutePath());
21958            }
21959            return codePaths;
21960        }
21961    }
21962
21963    /**
21964     * Examine all apps present on given mounted volume, and destroy apps that
21965     * aren't expected, either due to uninstallation or reinstallation on
21966     * another volume.
21967     */
21968    private void reconcileApps(String volumeUuid) {
21969        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21970        List<File> filesToDelete = null;
21971
21972        final File[] files = FileUtils.listFilesOrEmpty(
21973                Environment.getDataAppDirectory(volumeUuid));
21974        for (File file : files) {
21975            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21976                    && !PackageInstallerService.isStageName(file.getName());
21977            if (!isPackage) {
21978                // Ignore entries which are not packages
21979                continue;
21980            }
21981
21982            String absolutePath = file.getAbsolutePath();
21983
21984            boolean pathValid = false;
21985            final int absoluteCodePathCount = absoluteCodePaths.size();
21986            for (int i = 0; i < absoluteCodePathCount; i++) {
21987                String absoluteCodePath = absoluteCodePaths.get(i);
21988                if (absolutePath.startsWith(absoluteCodePath)) {
21989                    pathValid = true;
21990                    break;
21991                }
21992            }
21993
21994            if (!pathValid) {
21995                if (filesToDelete == null) {
21996                    filesToDelete = new ArrayList<>();
21997                }
21998                filesToDelete.add(file);
21999            }
22000        }
22001
22002        if (filesToDelete != null) {
22003            final int fileToDeleteCount = filesToDelete.size();
22004            for (int i = 0; i < fileToDeleteCount; i++) {
22005                File fileToDelete = filesToDelete.get(i);
22006                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22007                synchronized (mInstallLock) {
22008                    removeCodePathLI(fileToDelete);
22009                }
22010            }
22011        }
22012    }
22013
22014    /**
22015     * Reconcile all app data for the given user.
22016     * <p>
22017     * Verifies that directories exist and that ownership and labeling is
22018     * correct for all installed apps on all mounted volumes.
22019     */
22020    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22021        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22022        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22023            final String volumeUuid = vol.getFsUuid();
22024            synchronized (mInstallLock) {
22025                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22026            }
22027        }
22028    }
22029
22030    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22031            boolean migrateAppData) {
22032        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22033    }
22034
22035    /**
22036     * Reconcile all app data on given mounted volume.
22037     * <p>
22038     * Destroys app data that isn't expected, either due to uninstallation or
22039     * reinstallation on another volume.
22040     * <p>
22041     * Verifies that directories exist and that ownership and labeling is
22042     * correct for all installed apps.
22043     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22044     */
22045    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22046            boolean migrateAppData, boolean onlyCoreApps) {
22047        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22048                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22049        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22050
22051        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22052        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22053
22054        // First look for stale data that doesn't belong, and check if things
22055        // have changed since we did our last restorecon
22056        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22057            if (StorageManager.isFileEncryptedNativeOrEmulated()
22058                    && !StorageManager.isUserKeyUnlocked(userId)) {
22059                throw new RuntimeException(
22060                        "Yikes, someone asked us to reconcile CE storage while " + userId
22061                                + " was still locked; this would have caused massive data loss!");
22062            }
22063
22064            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22065            for (File file : files) {
22066                final String packageName = file.getName();
22067                try {
22068                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22069                } catch (PackageManagerException e) {
22070                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22071                    try {
22072                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22073                                StorageManager.FLAG_STORAGE_CE, 0);
22074                    } catch (InstallerException e2) {
22075                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22076                    }
22077                }
22078            }
22079        }
22080        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22081            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22082            for (File file : files) {
22083                final String packageName = file.getName();
22084                try {
22085                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22086                } catch (PackageManagerException e) {
22087                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22088                    try {
22089                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22090                                StorageManager.FLAG_STORAGE_DE, 0);
22091                    } catch (InstallerException e2) {
22092                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22093                    }
22094                }
22095            }
22096        }
22097
22098        // Ensure that data directories are ready to roll for all packages
22099        // installed for this volume and user
22100        final List<PackageSetting> packages;
22101        synchronized (mPackages) {
22102            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22103        }
22104        int preparedCount = 0;
22105        for (PackageSetting ps : packages) {
22106            final String packageName = ps.name;
22107            if (ps.pkg == null) {
22108                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22109                // TODO: might be due to legacy ASEC apps; we should circle back
22110                // and reconcile again once they're scanned
22111                continue;
22112            }
22113            // Skip non-core apps if requested
22114            if (onlyCoreApps && !ps.pkg.coreApp) {
22115                result.add(packageName);
22116                continue;
22117            }
22118
22119            if (ps.getInstalled(userId)) {
22120                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22121                preparedCount++;
22122            }
22123        }
22124
22125        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22126        return result;
22127    }
22128
22129    /**
22130     * Prepare app data for the given app just after it was installed or
22131     * upgraded. This method carefully only touches users that it's installed
22132     * for, and it forces a restorecon to handle any seinfo changes.
22133     * <p>
22134     * Verifies that directories exist and that ownership and labeling is
22135     * correct for all installed apps. If there is an ownership mismatch, it
22136     * will try recovering system apps by wiping data; third-party app data is
22137     * left intact.
22138     * <p>
22139     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22140     */
22141    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22142        final PackageSetting ps;
22143        synchronized (mPackages) {
22144            ps = mSettings.mPackages.get(pkg.packageName);
22145            mSettings.writeKernelMappingLPr(ps);
22146        }
22147
22148        final UserManager um = mContext.getSystemService(UserManager.class);
22149        UserManagerInternal umInternal = getUserManagerInternal();
22150        for (UserInfo user : um.getUsers()) {
22151            final int flags;
22152            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22153                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22154            } else if (umInternal.isUserRunning(user.id)) {
22155                flags = StorageManager.FLAG_STORAGE_DE;
22156            } else {
22157                continue;
22158            }
22159
22160            if (ps.getInstalled(user.id)) {
22161                // TODO: when user data is locked, mark that we're still dirty
22162                prepareAppDataLIF(pkg, user.id, flags);
22163            }
22164        }
22165    }
22166
22167    /**
22168     * Prepare app data for the given app.
22169     * <p>
22170     * Verifies that directories exist and that ownership and labeling is
22171     * correct for all installed apps. If there is an ownership mismatch, this
22172     * will try recovering system apps by wiping data; third-party app data is
22173     * left intact.
22174     */
22175    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22176        if (pkg == null) {
22177            Slog.wtf(TAG, "Package was null!", new Throwable());
22178            return;
22179        }
22180        prepareAppDataLeafLIF(pkg, userId, flags);
22181        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22182        for (int i = 0; i < childCount; i++) {
22183            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22184        }
22185    }
22186
22187    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22188            boolean maybeMigrateAppData) {
22189        prepareAppDataLIF(pkg, userId, flags);
22190
22191        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22192            // We may have just shuffled around app data directories, so
22193            // prepare them one more time
22194            prepareAppDataLIF(pkg, userId, flags);
22195        }
22196    }
22197
22198    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22199        if (DEBUG_APP_DATA) {
22200            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22201                    + Integer.toHexString(flags));
22202        }
22203
22204        final String volumeUuid = pkg.volumeUuid;
22205        final String packageName = pkg.packageName;
22206        final ApplicationInfo app = pkg.applicationInfo;
22207        final int appId = UserHandle.getAppId(app.uid);
22208
22209        Preconditions.checkNotNull(app.seInfo);
22210
22211        long ceDataInode = -1;
22212        try {
22213            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22214                    appId, app.seInfo, app.targetSdkVersion);
22215        } catch (InstallerException e) {
22216            if (app.isSystemApp()) {
22217                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22218                        + ", but trying to recover: " + e);
22219                destroyAppDataLeafLIF(pkg, userId, flags);
22220                try {
22221                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22222                            appId, app.seInfo, app.targetSdkVersion);
22223                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22224                } catch (InstallerException e2) {
22225                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22226                }
22227            } else {
22228                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22229            }
22230        }
22231
22232        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22233            // TODO: mark this structure as dirty so we persist it!
22234            synchronized (mPackages) {
22235                final PackageSetting ps = mSettings.mPackages.get(packageName);
22236                if (ps != null) {
22237                    ps.setCeDataInode(ceDataInode, userId);
22238                }
22239            }
22240        }
22241
22242        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22243    }
22244
22245    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22246        if (pkg == null) {
22247            Slog.wtf(TAG, "Package was null!", new Throwable());
22248            return;
22249        }
22250        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22251        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22252        for (int i = 0; i < childCount; i++) {
22253            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22254        }
22255    }
22256
22257    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22258        final String volumeUuid = pkg.volumeUuid;
22259        final String packageName = pkg.packageName;
22260        final ApplicationInfo app = pkg.applicationInfo;
22261
22262        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22263            // Create a native library symlink only if we have native libraries
22264            // and if the native libraries are 32 bit libraries. We do not provide
22265            // this symlink for 64 bit libraries.
22266            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22267                final String nativeLibPath = app.nativeLibraryDir;
22268                try {
22269                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22270                            nativeLibPath, userId);
22271                } catch (InstallerException e) {
22272                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22273                }
22274            }
22275        }
22276    }
22277
22278    /**
22279     * For system apps on non-FBE devices, this method migrates any existing
22280     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22281     * requested by the app.
22282     */
22283    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22284        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22285                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22286            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22287                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22288            try {
22289                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22290                        storageTarget);
22291            } catch (InstallerException e) {
22292                logCriticalInfo(Log.WARN,
22293                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22294            }
22295            return true;
22296        } else {
22297            return false;
22298        }
22299    }
22300
22301    public PackageFreezer freezePackage(String packageName, String killReason) {
22302        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22303    }
22304
22305    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22306        return new PackageFreezer(packageName, userId, killReason);
22307    }
22308
22309    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22310            String killReason) {
22311        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22312    }
22313
22314    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22315            String killReason) {
22316        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22317            return new PackageFreezer();
22318        } else {
22319            return freezePackage(packageName, userId, killReason);
22320        }
22321    }
22322
22323    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22324            String killReason) {
22325        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22326    }
22327
22328    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22329            String killReason) {
22330        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22331            return new PackageFreezer();
22332        } else {
22333            return freezePackage(packageName, userId, killReason);
22334        }
22335    }
22336
22337    /**
22338     * Class that freezes and kills the given package upon creation, and
22339     * unfreezes it upon closing. This is typically used when doing surgery on
22340     * app code/data to prevent the app from running while you're working.
22341     */
22342    private class PackageFreezer implements AutoCloseable {
22343        private final String mPackageName;
22344        private final PackageFreezer[] mChildren;
22345
22346        private final boolean mWeFroze;
22347
22348        private final AtomicBoolean mClosed = new AtomicBoolean();
22349        private final CloseGuard mCloseGuard = CloseGuard.get();
22350
22351        /**
22352         * Create and return a stub freezer that doesn't actually do anything,
22353         * typically used when someone requested
22354         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22355         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22356         */
22357        public PackageFreezer() {
22358            mPackageName = null;
22359            mChildren = null;
22360            mWeFroze = false;
22361            mCloseGuard.open("close");
22362        }
22363
22364        public PackageFreezer(String packageName, int userId, String killReason) {
22365            synchronized (mPackages) {
22366                mPackageName = packageName;
22367                mWeFroze = mFrozenPackages.add(mPackageName);
22368
22369                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22370                if (ps != null) {
22371                    killApplication(ps.name, ps.appId, userId, killReason);
22372                }
22373
22374                final PackageParser.Package p = mPackages.get(packageName);
22375                if (p != null && p.childPackages != null) {
22376                    final int N = p.childPackages.size();
22377                    mChildren = new PackageFreezer[N];
22378                    for (int i = 0; i < N; i++) {
22379                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22380                                userId, killReason);
22381                    }
22382                } else {
22383                    mChildren = null;
22384                }
22385            }
22386            mCloseGuard.open("close");
22387        }
22388
22389        @Override
22390        protected void finalize() throws Throwable {
22391            try {
22392                mCloseGuard.warnIfOpen();
22393                close();
22394            } finally {
22395                super.finalize();
22396            }
22397        }
22398
22399        @Override
22400        public void close() {
22401            mCloseGuard.close();
22402            if (mClosed.compareAndSet(false, true)) {
22403                synchronized (mPackages) {
22404                    if (mWeFroze) {
22405                        mFrozenPackages.remove(mPackageName);
22406                    }
22407
22408                    if (mChildren != null) {
22409                        for (PackageFreezer freezer : mChildren) {
22410                            freezer.close();
22411                        }
22412                    }
22413                }
22414            }
22415        }
22416    }
22417
22418    /**
22419     * Verify that given package is currently frozen.
22420     */
22421    private void checkPackageFrozen(String packageName) {
22422        synchronized (mPackages) {
22423            if (!mFrozenPackages.contains(packageName)) {
22424                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22425            }
22426        }
22427    }
22428
22429    @Override
22430    public int movePackage(final String packageName, final String volumeUuid) {
22431        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22432
22433        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22434        final int moveId = mNextMoveId.getAndIncrement();
22435        mHandler.post(new Runnable() {
22436            @Override
22437            public void run() {
22438                try {
22439                    movePackageInternal(packageName, volumeUuid, moveId, user);
22440                } catch (PackageManagerException e) {
22441                    Slog.w(TAG, "Failed to move " + packageName, e);
22442                    mMoveCallbacks.notifyStatusChanged(moveId,
22443                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22444                }
22445            }
22446        });
22447        return moveId;
22448    }
22449
22450    private void movePackageInternal(final String packageName, final String volumeUuid,
22451            final int moveId, UserHandle user) throws PackageManagerException {
22452        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22453        final PackageManager pm = mContext.getPackageManager();
22454
22455        final boolean currentAsec;
22456        final String currentVolumeUuid;
22457        final File codeFile;
22458        final String installerPackageName;
22459        final String packageAbiOverride;
22460        final int appId;
22461        final String seinfo;
22462        final String label;
22463        final int targetSdkVersion;
22464        final PackageFreezer freezer;
22465        final int[] installedUserIds;
22466
22467        // reader
22468        synchronized (mPackages) {
22469            final PackageParser.Package pkg = mPackages.get(packageName);
22470            final PackageSetting ps = mSettings.mPackages.get(packageName);
22471            if (pkg == null || ps == null) {
22472                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22473            }
22474
22475            if (pkg.applicationInfo.isSystemApp()) {
22476                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22477                        "Cannot move system application");
22478            }
22479
22480            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22481            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22482                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22483            if (isInternalStorage && !allow3rdPartyOnInternal) {
22484                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22485                        "3rd party apps are not allowed on internal storage");
22486            }
22487
22488            if (pkg.applicationInfo.isExternalAsec()) {
22489                currentAsec = true;
22490                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22491            } else if (pkg.applicationInfo.isForwardLocked()) {
22492                currentAsec = true;
22493                currentVolumeUuid = "forward_locked";
22494            } else {
22495                currentAsec = false;
22496                currentVolumeUuid = ps.volumeUuid;
22497
22498                final File probe = new File(pkg.codePath);
22499                final File probeOat = new File(probe, "oat");
22500                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22501                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22502                            "Move only supported for modern cluster style installs");
22503                }
22504            }
22505
22506            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22507                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22508                        "Package already moved to " + volumeUuid);
22509            }
22510            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22511                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22512                        "Device admin cannot be moved");
22513            }
22514
22515            if (mFrozenPackages.contains(packageName)) {
22516                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22517                        "Failed to move already frozen package");
22518            }
22519
22520            codeFile = new File(pkg.codePath);
22521            installerPackageName = ps.installerPackageName;
22522            packageAbiOverride = ps.cpuAbiOverrideString;
22523            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22524            seinfo = pkg.applicationInfo.seInfo;
22525            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22526            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22527            freezer = freezePackage(packageName, "movePackageInternal");
22528            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22529        }
22530
22531        final Bundle extras = new Bundle();
22532        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22533        extras.putString(Intent.EXTRA_TITLE, label);
22534        mMoveCallbacks.notifyCreated(moveId, extras);
22535
22536        int installFlags;
22537        final boolean moveCompleteApp;
22538        final File measurePath;
22539
22540        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22541            installFlags = INSTALL_INTERNAL;
22542            moveCompleteApp = !currentAsec;
22543            measurePath = Environment.getDataAppDirectory(volumeUuid);
22544        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22545            installFlags = INSTALL_EXTERNAL;
22546            moveCompleteApp = false;
22547            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22548        } else {
22549            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22550            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22551                    || !volume.isMountedWritable()) {
22552                freezer.close();
22553                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22554                        "Move location not mounted private volume");
22555            }
22556
22557            Preconditions.checkState(!currentAsec);
22558
22559            installFlags = INSTALL_INTERNAL;
22560            moveCompleteApp = true;
22561            measurePath = Environment.getDataAppDirectory(volumeUuid);
22562        }
22563
22564        final PackageStats stats = new PackageStats(null, -1);
22565        synchronized (mInstaller) {
22566            for (int userId : installedUserIds) {
22567                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22568                    freezer.close();
22569                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22570                            "Failed to measure package size");
22571                }
22572            }
22573        }
22574
22575        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22576                + stats.dataSize);
22577
22578        final long startFreeBytes = measurePath.getUsableSpace();
22579        final long sizeBytes;
22580        if (moveCompleteApp) {
22581            sizeBytes = stats.codeSize + stats.dataSize;
22582        } else {
22583            sizeBytes = stats.codeSize;
22584        }
22585
22586        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22587            freezer.close();
22588            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22589                    "Not enough free space to move");
22590        }
22591
22592        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22593
22594        final CountDownLatch installedLatch = new CountDownLatch(1);
22595        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22596            @Override
22597            public void onUserActionRequired(Intent intent) throws RemoteException {
22598                throw new IllegalStateException();
22599            }
22600
22601            @Override
22602            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22603                    Bundle extras) throws RemoteException {
22604                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22605                        + PackageManager.installStatusToString(returnCode, msg));
22606
22607                installedLatch.countDown();
22608                freezer.close();
22609
22610                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22611                switch (status) {
22612                    case PackageInstaller.STATUS_SUCCESS:
22613                        mMoveCallbacks.notifyStatusChanged(moveId,
22614                                PackageManager.MOVE_SUCCEEDED);
22615                        break;
22616                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22617                        mMoveCallbacks.notifyStatusChanged(moveId,
22618                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22619                        break;
22620                    default:
22621                        mMoveCallbacks.notifyStatusChanged(moveId,
22622                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22623                        break;
22624                }
22625            }
22626        };
22627
22628        final MoveInfo move;
22629        if (moveCompleteApp) {
22630            // Kick off a thread to report progress estimates
22631            new Thread() {
22632                @Override
22633                public void run() {
22634                    while (true) {
22635                        try {
22636                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22637                                break;
22638                            }
22639                        } catch (InterruptedException ignored) {
22640                        }
22641
22642                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22643                        final int progress = 10 + (int) MathUtils.constrain(
22644                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22645                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22646                    }
22647                }
22648            }.start();
22649
22650            final String dataAppName = codeFile.getName();
22651            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22652                    dataAppName, appId, seinfo, targetSdkVersion);
22653        } else {
22654            move = null;
22655        }
22656
22657        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22658
22659        final Message msg = mHandler.obtainMessage(INIT_COPY);
22660        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22661        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22662                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22663                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22664                PackageManager.INSTALL_REASON_UNKNOWN);
22665        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22666        msg.obj = params;
22667
22668        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22669                System.identityHashCode(msg.obj));
22670        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22671                System.identityHashCode(msg.obj));
22672
22673        mHandler.sendMessage(msg);
22674    }
22675
22676    @Override
22677    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22678        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22679
22680        final int realMoveId = mNextMoveId.getAndIncrement();
22681        final Bundle extras = new Bundle();
22682        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22683        mMoveCallbacks.notifyCreated(realMoveId, extras);
22684
22685        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22686            @Override
22687            public void onCreated(int moveId, Bundle extras) {
22688                // Ignored
22689            }
22690
22691            @Override
22692            public void onStatusChanged(int moveId, int status, long estMillis) {
22693                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22694            }
22695        };
22696
22697        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22698        storage.setPrimaryStorageUuid(volumeUuid, callback);
22699        return realMoveId;
22700    }
22701
22702    @Override
22703    public int getMoveStatus(int moveId) {
22704        mContext.enforceCallingOrSelfPermission(
22705                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22706        return mMoveCallbacks.mLastStatus.get(moveId);
22707    }
22708
22709    @Override
22710    public void registerMoveCallback(IPackageMoveObserver callback) {
22711        mContext.enforceCallingOrSelfPermission(
22712                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22713        mMoveCallbacks.register(callback);
22714    }
22715
22716    @Override
22717    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22718        mContext.enforceCallingOrSelfPermission(
22719                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22720        mMoveCallbacks.unregister(callback);
22721    }
22722
22723    @Override
22724    public boolean setInstallLocation(int loc) {
22725        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22726                null);
22727        if (getInstallLocation() == loc) {
22728            return true;
22729        }
22730        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22731                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22732            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22733                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22734            return true;
22735        }
22736        return false;
22737   }
22738
22739    @Override
22740    public int getInstallLocation() {
22741        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22742                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22743                PackageHelper.APP_INSTALL_AUTO);
22744    }
22745
22746    /** Called by UserManagerService */
22747    void cleanUpUser(UserManagerService userManager, int userHandle) {
22748        synchronized (mPackages) {
22749            mDirtyUsers.remove(userHandle);
22750            mUserNeedsBadging.delete(userHandle);
22751            mSettings.removeUserLPw(userHandle);
22752            mPendingBroadcasts.remove(userHandle);
22753            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22754            removeUnusedPackagesLPw(userManager, userHandle);
22755        }
22756    }
22757
22758    /**
22759     * We're removing userHandle and would like to remove any downloaded packages
22760     * that are no longer in use by any other user.
22761     * @param userHandle the user being removed
22762     */
22763    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22764        final boolean DEBUG_CLEAN_APKS = false;
22765        int [] users = userManager.getUserIds();
22766        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22767        while (psit.hasNext()) {
22768            PackageSetting ps = psit.next();
22769            if (ps.pkg == null) {
22770                continue;
22771            }
22772            final String packageName = ps.pkg.packageName;
22773            // Skip over if system app
22774            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22775                continue;
22776            }
22777            if (DEBUG_CLEAN_APKS) {
22778                Slog.i(TAG, "Checking package " + packageName);
22779            }
22780            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22781            if (keep) {
22782                if (DEBUG_CLEAN_APKS) {
22783                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22784                }
22785            } else {
22786                for (int i = 0; i < users.length; i++) {
22787                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22788                        keep = true;
22789                        if (DEBUG_CLEAN_APKS) {
22790                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22791                                    + users[i]);
22792                        }
22793                        break;
22794                    }
22795                }
22796            }
22797            if (!keep) {
22798                if (DEBUG_CLEAN_APKS) {
22799                    Slog.i(TAG, "  Removing package " + packageName);
22800                }
22801                mHandler.post(new Runnable() {
22802                    public void run() {
22803                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22804                                userHandle, 0);
22805                    } //end run
22806                });
22807            }
22808        }
22809    }
22810
22811    /** Called by UserManagerService */
22812    void createNewUser(int userId, String[] disallowedPackages) {
22813        synchronized (mInstallLock) {
22814            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22815        }
22816        synchronized (mPackages) {
22817            scheduleWritePackageRestrictionsLocked(userId);
22818            scheduleWritePackageListLocked(userId);
22819            applyFactoryDefaultBrowserLPw(userId);
22820            primeDomainVerificationsLPw(userId);
22821        }
22822    }
22823
22824    void onNewUserCreated(final int userId) {
22825        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22826        // If permission review for legacy apps is required, we represent
22827        // dagerous permissions for such apps as always granted runtime
22828        // permissions to keep per user flag state whether review is needed.
22829        // Hence, if a new user is added we have to propagate dangerous
22830        // permission grants for these legacy apps.
22831        if (mPermissionReviewRequired) {
22832            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22833                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22834        }
22835    }
22836
22837    @Override
22838    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22839        mContext.enforceCallingOrSelfPermission(
22840                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22841                "Only package verification agents can read the verifier device identity");
22842
22843        synchronized (mPackages) {
22844            return mSettings.getVerifierDeviceIdentityLPw();
22845        }
22846    }
22847
22848    @Override
22849    public void setPermissionEnforced(String permission, boolean enforced) {
22850        // TODO: Now that we no longer change GID for storage, this should to away.
22851        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22852                "setPermissionEnforced");
22853        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22854            synchronized (mPackages) {
22855                if (mSettings.mReadExternalStorageEnforced == null
22856                        || mSettings.mReadExternalStorageEnforced != enforced) {
22857                    mSettings.mReadExternalStorageEnforced = enforced;
22858                    mSettings.writeLPr();
22859                }
22860            }
22861            // kill any non-foreground processes so we restart them and
22862            // grant/revoke the GID.
22863            final IActivityManager am = ActivityManager.getService();
22864            if (am != null) {
22865                final long token = Binder.clearCallingIdentity();
22866                try {
22867                    am.killProcessesBelowForeground("setPermissionEnforcement");
22868                } catch (RemoteException e) {
22869                } finally {
22870                    Binder.restoreCallingIdentity(token);
22871                }
22872            }
22873        } else {
22874            throw new IllegalArgumentException("No selective enforcement for " + permission);
22875        }
22876    }
22877
22878    @Override
22879    @Deprecated
22880    public boolean isPermissionEnforced(String permission) {
22881        return true;
22882    }
22883
22884    @Override
22885    public boolean isStorageLow() {
22886        final long token = Binder.clearCallingIdentity();
22887        try {
22888            final DeviceStorageMonitorInternal
22889                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22890            if (dsm != null) {
22891                return dsm.isMemoryLow();
22892            } else {
22893                return false;
22894            }
22895        } finally {
22896            Binder.restoreCallingIdentity(token);
22897        }
22898    }
22899
22900    @Override
22901    public IPackageInstaller getPackageInstaller() {
22902        return mInstallerService;
22903    }
22904
22905    private boolean userNeedsBadging(int userId) {
22906        int index = mUserNeedsBadging.indexOfKey(userId);
22907        if (index < 0) {
22908            final UserInfo userInfo;
22909            final long token = Binder.clearCallingIdentity();
22910            try {
22911                userInfo = sUserManager.getUserInfo(userId);
22912            } finally {
22913                Binder.restoreCallingIdentity(token);
22914            }
22915            final boolean b;
22916            if (userInfo != null && userInfo.isManagedProfile()) {
22917                b = true;
22918            } else {
22919                b = false;
22920            }
22921            mUserNeedsBadging.put(userId, b);
22922            return b;
22923        }
22924        return mUserNeedsBadging.valueAt(index);
22925    }
22926
22927    @Override
22928    public KeySet getKeySetByAlias(String packageName, String alias) {
22929        if (packageName == null || alias == null) {
22930            return null;
22931        }
22932        synchronized(mPackages) {
22933            final PackageParser.Package pkg = mPackages.get(packageName);
22934            if (pkg == null) {
22935                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22936                throw new IllegalArgumentException("Unknown package: " + packageName);
22937            }
22938            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22939            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22940        }
22941    }
22942
22943    @Override
22944    public KeySet getSigningKeySet(String packageName) {
22945        if (packageName == null) {
22946            return null;
22947        }
22948        synchronized(mPackages) {
22949            final PackageParser.Package pkg = mPackages.get(packageName);
22950            if (pkg == null) {
22951                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22952                throw new IllegalArgumentException("Unknown package: " + packageName);
22953            }
22954            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22955                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22956                throw new SecurityException("May not access signing KeySet of other apps.");
22957            }
22958            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22959            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22960        }
22961    }
22962
22963    @Override
22964    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22965        if (packageName == null || ks == null) {
22966            return false;
22967        }
22968        synchronized(mPackages) {
22969            final PackageParser.Package pkg = mPackages.get(packageName);
22970            if (pkg == null) {
22971                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22972                throw new IllegalArgumentException("Unknown package: " + packageName);
22973            }
22974            IBinder ksh = ks.getToken();
22975            if (ksh instanceof KeySetHandle) {
22976                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22977                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22978            }
22979            return false;
22980        }
22981    }
22982
22983    @Override
22984    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22985        if (packageName == null || ks == null) {
22986            return false;
22987        }
22988        synchronized(mPackages) {
22989            final PackageParser.Package pkg = mPackages.get(packageName);
22990            if (pkg == null) {
22991                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22992                throw new IllegalArgumentException("Unknown package: " + packageName);
22993            }
22994            IBinder ksh = ks.getToken();
22995            if (ksh instanceof KeySetHandle) {
22996                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22997                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22998            }
22999            return false;
23000        }
23001    }
23002
23003    private void deletePackageIfUnusedLPr(final String packageName) {
23004        PackageSetting ps = mSettings.mPackages.get(packageName);
23005        if (ps == null) {
23006            return;
23007        }
23008        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23009            // TODO Implement atomic delete if package is unused
23010            // It is currently possible that the package will be deleted even if it is installed
23011            // after this method returns.
23012            mHandler.post(new Runnable() {
23013                public void run() {
23014                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23015                            0, PackageManager.DELETE_ALL_USERS);
23016                }
23017            });
23018        }
23019    }
23020
23021    /**
23022     * Check and throw if the given before/after packages would be considered a
23023     * downgrade.
23024     */
23025    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23026            throws PackageManagerException {
23027        if (after.versionCode < before.mVersionCode) {
23028            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23029                    "Update version code " + after.versionCode + " is older than current "
23030                    + before.mVersionCode);
23031        } else if (after.versionCode == before.mVersionCode) {
23032            if (after.baseRevisionCode < before.baseRevisionCode) {
23033                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23034                        "Update base revision code " + after.baseRevisionCode
23035                        + " is older than current " + before.baseRevisionCode);
23036            }
23037
23038            if (!ArrayUtils.isEmpty(after.splitNames)) {
23039                for (int i = 0; i < after.splitNames.length; i++) {
23040                    final String splitName = after.splitNames[i];
23041                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23042                    if (j != -1) {
23043                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23044                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23045                                    "Update split " + splitName + " revision code "
23046                                    + after.splitRevisionCodes[i] + " is older than current "
23047                                    + before.splitRevisionCodes[j]);
23048                        }
23049                    }
23050                }
23051            }
23052        }
23053    }
23054
23055    private static class MoveCallbacks extends Handler {
23056        private static final int MSG_CREATED = 1;
23057        private static final int MSG_STATUS_CHANGED = 2;
23058
23059        private final RemoteCallbackList<IPackageMoveObserver>
23060                mCallbacks = new RemoteCallbackList<>();
23061
23062        private final SparseIntArray mLastStatus = new SparseIntArray();
23063
23064        public MoveCallbacks(Looper looper) {
23065            super(looper);
23066        }
23067
23068        public void register(IPackageMoveObserver callback) {
23069            mCallbacks.register(callback);
23070        }
23071
23072        public void unregister(IPackageMoveObserver callback) {
23073            mCallbacks.unregister(callback);
23074        }
23075
23076        @Override
23077        public void handleMessage(Message msg) {
23078            final SomeArgs args = (SomeArgs) msg.obj;
23079            final int n = mCallbacks.beginBroadcast();
23080            for (int i = 0; i < n; i++) {
23081                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23082                try {
23083                    invokeCallback(callback, msg.what, args);
23084                } catch (RemoteException ignored) {
23085                }
23086            }
23087            mCallbacks.finishBroadcast();
23088            args.recycle();
23089        }
23090
23091        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23092                throws RemoteException {
23093            switch (what) {
23094                case MSG_CREATED: {
23095                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23096                    break;
23097                }
23098                case MSG_STATUS_CHANGED: {
23099                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23100                    break;
23101                }
23102            }
23103        }
23104
23105        private void notifyCreated(int moveId, Bundle extras) {
23106            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23107
23108            final SomeArgs args = SomeArgs.obtain();
23109            args.argi1 = moveId;
23110            args.arg2 = extras;
23111            obtainMessage(MSG_CREATED, args).sendToTarget();
23112        }
23113
23114        private void notifyStatusChanged(int moveId, int status) {
23115            notifyStatusChanged(moveId, status, -1);
23116        }
23117
23118        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23119            Slog.v(TAG, "Move " + moveId + " status " + status);
23120
23121            final SomeArgs args = SomeArgs.obtain();
23122            args.argi1 = moveId;
23123            args.argi2 = status;
23124            args.arg3 = estMillis;
23125            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23126
23127            synchronized (mLastStatus) {
23128                mLastStatus.put(moveId, status);
23129            }
23130        }
23131    }
23132
23133    private final static class OnPermissionChangeListeners extends Handler {
23134        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23135
23136        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23137                new RemoteCallbackList<>();
23138
23139        public OnPermissionChangeListeners(Looper looper) {
23140            super(looper);
23141        }
23142
23143        @Override
23144        public void handleMessage(Message msg) {
23145            switch (msg.what) {
23146                case MSG_ON_PERMISSIONS_CHANGED: {
23147                    final int uid = msg.arg1;
23148                    handleOnPermissionsChanged(uid);
23149                } break;
23150            }
23151        }
23152
23153        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23154            mPermissionListeners.register(listener);
23155
23156        }
23157
23158        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23159            mPermissionListeners.unregister(listener);
23160        }
23161
23162        public void onPermissionsChanged(int uid) {
23163            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23164                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23165            }
23166        }
23167
23168        private void handleOnPermissionsChanged(int uid) {
23169            final int count = mPermissionListeners.beginBroadcast();
23170            try {
23171                for (int i = 0; i < count; i++) {
23172                    IOnPermissionsChangeListener callback = mPermissionListeners
23173                            .getBroadcastItem(i);
23174                    try {
23175                        callback.onPermissionsChanged(uid);
23176                    } catch (RemoteException e) {
23177                        Log.e(TAG, "Permission listener is dead", e);
23178                    }
23179                }
23180            } finally {
23181                mPermissionListeners.finishBroadcast();
23182            }
23183        }
23184    }
23185
23186    private class PackageManagerInternalImpl extends PackageManagerInternal {
23187        @Override
23188        public void setLocationPackagesProvider(PackagesProvider provider) {
23189            synchronized (mPackages) {
23190                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23191            }
23192        }
23193
23194        @Override
23195        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23196            synchronized (mPackages) {
23197                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23198            }
23199        }
23200
23201        @Override
23202        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23203            synchronized (mPackages) {
23204                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23205            }
23206        }
23207
23208        @Override
23209        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23210            synchronized (mPackages) {
23211                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23212            }
23213        }
23214
23215        @Override
23216        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23217            synchronized (mPackages) {
23218                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23219            }
23220        }
23221
23222        @Override
23223        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23224            synchronized (mPackages) {
23225                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23226            }
23227        }
23228
23229        @Override
23230        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23231            synchronized (mPackages) {
23232                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23233                        packageName, userId);
23234            }
23235        }
23236
23237        @Override
23238        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23239            synchronized (mPackages) {
23240                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23241                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23242                        packageName, userId);
23243            }
23244        }
23245
23246        @Override
23247        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23248            synchronized (mPackages) {
23249                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23250                        packageName, userId);
23251            }
23252        }
23253
23254        @Override
23255        public void setKeepUninstalledPackages(final List<String> packageList) {
23256            Preconditions.checkNotNull(packageList);
23257            List<String> removedFromList = null;
23258            synchronized (mPackages) {
23259                if (mKeepUninstalledPackages != null) {
23260                    final int packagesCount = mKeepUninstalledPackages.size();
23261                    for (int i = 0; i < packagesCount; i++) {
23262                        String oldPackage = mKeepUninstalledPackages.get(i);
23263                        if (packageList != null && packageList.contains(oldPackage)) {
23264                            continue;
23265                        }
23266                        if (removedFromList == null) {
23267                            removedFromList = new ArrayList<>();
23268                        }
23269                        removedFromList.add(oldPackage);
23270                    }
23271                }
23272                mKeepUninstalledPackages = new ArrayList<>(packageList);
23273                if (removedFromList != null) {
23274                    final int removedCount = removedFromList.size();
23275                    for (int i = 0; i < removedCount; i++) {
23276                        deletePackageIfUnusedLPr(removedFromList.get(i));
23277                    }
23278                }
23279            }
23280        }
23281
23282        @Override
23283        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23284            synchronized (mPackages) {
23285                // If we do not support permission review, done.
23286                if (!mPermissionReviewRequired) {
23287                    return false;
23288                }
23289
23290                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23291                if (packageSetting == null) {
23292                    return false;
23293                }
23294
23295                // Permission review applies only to apps not supporting the new permission model.
23296                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23297                    return false;
23298                }
23299
23300                // Legacy apps have the permission and get user consent on launch.
23301                PermissionsState permissionsState = packageSetting.getPermissionsState();
23302                return permissionsState.isPermissionReviewRequired(userId);
23303            }
23304        }
23305
23306        @Override
23307        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23308            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23309        }
23310
23311        @Override
23312        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23313                int userId) {
23314            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23315        }
23316
23317        @Override
23318        public void setDeviceAndProfileOwnerPackages(
23319                int deviceOwnerUserId, String deviceOwnerPackage,
23320                SparseArray<String> profileOwnerPackages) {
23321            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23322                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23323        }
23324
23325        @Override
23326        public boolean isPackageDataProtected(int userId, String packageName) {
23327            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23328        }
23329
23330        @Override
23331        public boolean isPackageEphemeral(int userId, String packageName) {
23332            synchronized (mPackages) {
23333                final PackageSetting ps = mSettings.mPackages.get(packageName);
23334                return ps != null ? ps.getInstantApp(userId) : false;
23335            }
23336        }
23337
23338        @Override
23339        public boolean wasPackageEverLaunched(String packageName, int userId) {
23340            synchronized (mPackages) {
23341                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23342            }
23343        }
23344
23345        @Override
23346        public void grantRuntimePermission(String packageName, String name, int userId,
23347                boolean overridePolicy) {
23348            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23349                    overridePolicy);
23350        }
23351
23352        @Override
23353        public void revokeRuntimePermission(String packageName, String name, int userId,
23354                boolean overridePolicy) {
23355            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23356                    overridePolicy);
23357        }
23358
23359        @Override
23360        public String getNameForUid(int uid) {
23361            return PackageManagerService.this.getNameForUid(uid);
23362        }
23363
23364        @Override
23365        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23366                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23367            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23368                    responseObj, origIntent, resolvedType, callingPackage, userId);
23369        }
23370
23371        @Override
23372        public void grantEphemeralAccess(int userId, Intent intent,
23373                int targetAppId, int ephemeralAppId) {
23374            synchronized (mPackages) {
23375                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23376                        targetAppId, ephemeralAppId);
23377            }
23378        }
23379
23380        @Override
23381        public boolean isInstantAppInstallerComponent(ComponentName component) {
23382            synchronized (mPackages) {
23383                return mInstantAppInstallerActivity != null
23384                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23385            }
23386        }
23387
23388        @Override
23389        public void pruneInstantApps() {
23390            synchronized (mPackages) {
23391                mInstantAppRegistry.pruneInstantAppsLPw();
23392            }
23393        }
23394
23395        @Override
23396        public String getSetupWizardPackageName() {
23397            return mSetupWizardPackage;
23398        }
23399
23400        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23401            if (policy != null) {
23402                mExternalSourcesPolicy = policy;
23403            }
23404        }
23405
23406        @Override
23407        public boolean isPackagePersistent(String packageName) {
23408            synchronized (mPackages) {
23409                PackageParser.Package pkg = mPackages.get(packageName);
23410                return pkg != null
23411                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23412                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23413                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23414                        : false;
23415            }
23416        }
23417
23418        @Override
23419        public List<PackageInfo> getOverlayPackages(int userId) {
23420            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23421            synchronized (mPackages) {
23422                for (PackageParser.Package p : mPackages.values()) {
23423                    if (p.mOverlayTarget != null) {
23424                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23425                        if (pkg != null) {
23426                            overlayPackages.add(pkg);
23427                        }
23428                    }
23429                }
23430            }
23431            return overlayPackages;
23432        }
23433
23434        @Override
23435        public List<String> getTargetPackageNames(int userId) {
23436            List<String> targetPackages = new ArrayList<>();
23437            synchronized (mPackages) {
23438                for (PackageParser.Package p : mPackages.values()) {
23439                    if (p.mOverlayTarget == null) {
23440                        targetPackages.add(p.packageName);
23441                    }
23442                }
23443            }
23444            return targetPackages;
23445        }
23446
23447        @Override
23448        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23449                @Nullable List<String> overlayPackageNames) {
23450            synchronized (mPackages) {
23451                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23452                    Slog.e(TAG, "failed to find package " + targetPackageName);
23453                    return false;
23454                }
23455
23456                ArrayList<String> paths = null;
23457                if (overlayPackageNames != null) {
23458                    final int N = overlayPackageNames.size();
23459                    paths = new ArrayList<>(N);
23460                    for (int i = 0; i < N; i++) {
23461                        final String packageName = overlayPackageNames.get(i);
23462                        final PackageParser.Package pkg = mPackages.get(packageName);
23463                        if (pkg == null) {
23464                            Slog.e(TAG, "failed to find package " + packageName);
23465                            return false;
23466                        }
23467                        paths.add(pkg.baseCodePath);
23468                    }
23469                }
23470
23471                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23472                    mEnabledOverlayPaths.get(userId);
23473                if (userSpecificOverlays == null) {
23474                    userSpecificOverlays = new ArrayMap<>();
23475                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23476                }
23477
23478                if (paths != null && paths.size() > 0) {
23479                    userSpecificOverlays.put(targetPackageName, paths);
23480                } else {
23481                    userSpecificOverlays.remove(targetPackageName);
23482                }
23483                return true;
23484            }
23485        }
23486
23487        @Override
23488        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23489                int flags, int userId) {
23490            return resolveIntentInternal(
23491                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23492        }
23493
23494        @Override
23495        public ResolveInfo resolveService(Intent intent, String resolvedType,
23496                int flags, int userId, int callingUid) {
23497            return resolveServiceInternal(
23498                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23499        }
23500
23501        @Override
23502        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23503            synchronized (mPackages) {
23504                mIsolatedOwners.put(isolatedUid, ownerUid);
23505            }
23506        }
23507
23508        @Override
23509        public void removeIsolatedUid(int isolatedUid) {
23510            synchronized (mPackages) {
23511                mIsolatedOwners.delete(isolatedUid);
23512            }
23513        }
23514    }
23515
23516    @Override
23517    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23518        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23519        synchronized (mPackages) {
23520            final long identity = Binder.clearCallingIdentity();
23521            try {
23522                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23523                        packageNames, userId);
23524            } finally {
23525                Binder.restoreCallingIdentity(identity);
23526            }
23527        }
23528    }
23529
23530    @Override
23531    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23532        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23533        synchronized (mPackages) {
23534            final long identity = Binder.clearCallingIdentity();
23535            try {
23536                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23537                        packageNames, userId);
23538            } finally {
23539                Binder.restoreCallingIdentity(identity);
23540            }
23541        }
23542    }
23543
23544    private static void enforceSystemOrPhoneCaller(String tag) {
23545        int callingUid = Binder.getCallingUid();
23546        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23547            throw new SecurityException(
23548                    "Cannot call " + tag + " from UID " + callingUid);
23549        }
23550    }
23551
23552    boolean isHistoricalPackageUsageAvailable() {
23553        return mPackageUsage.isHistoricalPackageUsageAvailable();
23554    }
23555
23556    /**
23557     * Return a <b>copy</b> of the collection of packages known to the package manager.
23558     * @return A copy of the values of mPackages.
23559     */
23560    Collection<PackageParser.Package> getPackages() {
23561        synchronized (mPackages) {
23562            return new ArrayList<>(mPackages.values());
23563        }
23564    }
23565
23566    /**
23567     * Logs process start information (including base APK hash) to the security log.
23568     * @hide
23569     */
23570    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23571            String apkFile, int pid) {
23572        if (!SecurityLog.isLoggingEnabled()) {
23573            return;
23574        }
23575        Bundle data = new Bundle();
23576        data.putLong("startTimestamp", System.currentTimeMillis());
23577        data.putString("processName", processName);
23578        data.putInt("uid", uid);
23579        data.putString("seinfo", seinfo);
23580        data.putString("apkFile", apkFile);
23581        data.putInt("pid", pid);
23582        Message msg = mProcessLoggingHandler.obtainMessage(
23583                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23584        msg.setData(data);
23585        mProcessLoggingHandler.sendMessage(msg);
23586    }
23587
23588    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23589        return mCompilerStats.getPackageStats(pkgName);
23590    }
23591
23592    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23593        return getOrCreateCompilerPackageStats(pkg.packageName);
23594    }
23595
23596    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23597        return mCompilerStats.getOrCreatePackageStats(pkgName);
23598    }
23599
23600    public void deleteCompilerPackageStats(String pkgName) {
23601        mCompilerStats.deletePackageStats(pkgName);
23602    }
23603
23604    @Override
23605    public int getInstallReason(String packageName, int userId) {
23606        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23607                true /* requireFullPermission */, false /* checkShell */,
23608                "get install reason");
23609        synchronized (mPackages) {
23610            final PackageSetting ps = mSettings.mPackages.get(packageName);
23611            if (ps != null) {
23612                return ps.getInstallReason(userId);
23613            }
23614        }
23615        return PackageManager.INSTALL_REASON_UNKNOWN;
23616    }
23617
23618    @Override
23619    public boolean canRequestPackageInstalls(String packageName, int userId) {
23620        int callingUid = Binder.getCallingUid();
23621        int uid = getPackageUid(packageName, 0, userId);
23622        if (callingUid != uid && callingUid != Process.ROOT_UID
23623                && callingUid != Process.SYSTEM_UID) {
23624            throw new SecurityException(
23625                    "Caller uid " + callingUid + " does not own package " + packageName);
23626        }
23627        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23628        if (info == null) {
23629            return false;
23630        }
23631        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23632            throw new UnsupportedOperationException(
23633                    "Operation only supported on apps targeting Android O or higher");
23634        }
23635        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23636        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23637        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23638            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23639        }
23640        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23641            return false;
23642        }
23643        if (mExternalSourcesPolicy != null) {
23644            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23645            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23646                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23647            }
23648        }
23649        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23650    }
23651
23652    @Override
23653    public ComponentName getInstantAppResolverSettingsComponent() {
23654        return mInstantAppResolverSettingsComponent;
23655    }
23656
23657    @Override
23658    public ComponentName getInstantAppInstallerComponent() {
23659        return mInstantAppInstallerActivity == null
23660                ? null : mInstantAppInstallerActivity.getComponentName();
23661    }
23662
23663    @Override
23664    public String getInstantAppAndroidId(String packageName, int userId) {
23665        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23666                "getInstantAppAndroidId");
23667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23668                true /* requireFullPermission */, false /* checkShell */,
23669                "getInstantAppAndroidId");
23670        // Make sure the target is an Instant App.
23671        if (!isInstantApp(packageName, userId)) {
23672            return null;
23673        }
23674        synchronized (mPackages) {
23675            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23676        }
23677    }
23678}
23679
23680interface PackageSender {
23681    void sendPackageBroadcast(final String action, final String pkg,
23682        final Bundle extras, final int flags, final String targetPkg,
23683        final IIntentReceiver finishedReceiver, final int[] userIds);
23684    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23685        int appId, int... userIds);
23686}
23687